cfile-iofopenfclosefile-pointer

Is FILE * reassignment without fclose() okay?


Suppose I have the following code :

FILE *x = fopen("story.txt",r);
if(x!=NULL)
{
    x = fopen("story.txt",wb); /* <- Does this waste/leak memory ?? */
    /* ... do something .... */
    /* if(fclose(x)==EOF)...else... */
}
else
{
    printf("story.txt does not exist\n");
}

Here, I'm reassigning the pointer to where a buffer for story.txtwas created in memory , without fclose(x) , assuming that since it is a pointer, the memory area will simply be overwritten to with the ' new ' buffer. Is this assumption accurate ? Am I leaking or wasting memory , or is the approach okay ?


Solution

  • You just leaked a file handle. If you do it enough, you'll run out of open file handles to allocate, and all attempts to open a file will fail. Don't do that. fclose your FILE*s.

    There is no reason to think the "memory area" would be overwritten here; you're overwriting the pointer, not what it points to, and what it points to is the file related structures (stdio buffers, descriptor of the underlying kernel file handle, etc.). It no more overwrites the memory being pointed to than assigning a second malloc to the same pointer overwrites what the first malloc pointed to; you're leaking the first resource acquisition in both cases by losing the original pointer in favor of the new one.