I found this problem while working on recover.c. My program recovers all the image files, check50 says everything's cool, but when I run Valgrind, it gives me a ton of errors. After some tests, I found where the problem is: fwrite and fclose.

The way my program works is it opens a file, writes an image, closes the file, and repeats. All the files are opened with the same line: FILE* img = fopen(...);. Then I close the file with fclose(img);, and then I use again FILE* img = fopen(...); changing the name of the file, but not the pointer's name, which is always img. What the error output from Valgrind says is that there is an invalid read by fwrite(), happening inside a block previously freed by an earlier call to fclose().

I also noticed that the output when running the program through Valgrind is different than what I get from running the program alone.

Maybe this is what the man pages for fclose() are referring to when they say:

The behavior of fclose() is undefined if the stream parameter is an illegal pointer, or is a descriptor already passed to a previous invocation of fclose().

I've read some stack exchange answers saying this way of operating shouldn't be a problem, but I wonder if there is a better way of doing this. Hopefully you can clarify why this is happening and offer a better solution. Thanks.


OK, so it turns out there was already an answer to this on Reddit. The problem was that I was declaring my pointer again, instead of just reassigning.

In other words, I was doing:

FILE* img = fopen(...);, fclose(img), FILE* img = fopen(...);.

When I should be doing:

FILE* img = fopen(...);, fclose(img), img = fopen(...);.

Check out the reddit post for additional information:


You must log in to answer this question.

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