0

Please take a look at the codes (both correct and incorrect) first-

incorrect code-

    char* buffer = malloc(*counter);
    char* ch = malloc(sizeof(char));
    for (*ch=fgetc(file);*c != EOF;*ch=fgetc(file))
    {
        buffer[*i] = *ch;
        *i = *i + 1;
    }
    *content = buffer;

Then I changed

char* ch = malloc(sizeof(char));

to-

int* ch = malloc(sizeof(int));

And everything worked fine (of course only the static data, but that is not a point i want to make)

and then to-

int* ch = malloc(sizeof(char));

and still everything alright.

  1. What difference it makes to assign int* or char* to "ch".
  2. I specified int* ch and size of an Int in malloc (in first correction) but my buffer elements are still of type char and of size of a char. Then how the code still works?

1 Answer 1

1

Because of internal casting in fgetc, this char* ch = malloc(sizeof(char)); can return a "false eof", and almost always does on binary (image) files. Some char in the image files is being cast to the int -1. EOF is defined (in stdio.h) as -1. The loop ends prematurely. When you declare ch as an int (instead of char), it should work. This article may help clarify the point.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .