The program reads one byte at a time and essentially appends it to buffer
. So the number of bytes that buffer needs to hold increases each read. This buffer = realloc(buffer, sizeof(char));
allocates buffer for 1 byte every time. It needs to be at least as big as the number of bytes read. You're already keeping track of that so it should be an easy correction.
It is a problem to treat the bytes read as char
data. Valid char values are 0 - 127 (corresponding to the ASCII character set). Think about a white pixel from pset 4. That would be 3 bytes of 255,255,255. Image data does not "translate" to ascii. Therefore you should not "translate" the bytes read to char. Use int
here for (char c = fgetc(file); c != EOF; c = fgetc(file))
. And do not cast c
here buffer[size] = (char) c;
. Something like:
for (int c = fgetc(file); c != EOF; c = fgetc(file))
{
buffer[size] = c;
Another problem: free(buffer);
The memory for buffer has been allocated and will be "sent" back to main in *content. This free will "destroy" that memory when it returns to main, so content will contain "nothing". content will be free'd in main around line 1234. Do not free(buffer);
.