I’m running into this strange issue. Basically I have a loop that loops forever, in the beginning of that loop I open a file, I write some stuff to the file, then at the end of the loop I close the file. Works fine for the first iteration of the loop but on the second iteration I get
*** glibc detected *** ./prog: double free or corruption (top):
I have narrowed this down to the fclose(data) line during the second iteration of the loop. Apparently this error happens when you are freeing something more than once but how is that possible in this code?
while(1)
{
if (data == NULL)
{
data = fopen(data_path, "w+");
}
/* do a bunch of stuff... */
if (data != NULL)
{
fclose(data);
}
}
A stranger thing is that if I add the following line after fclose(data) the program runs just fine without any problems:
data = NULL;
Can someone who is better versed in C than me please explain what’s going on here?
fclose does not make the file pointer NULL.
It Simply closes the file.
So in the second iteration the file is not opened because data is not NULL.