I have a question about FILE pointer operations in C; specifically, what happens when a command uses a closed file pointer.
Here is an example
FILE *fp1;
fp1 = fopen(file1,"r");
function1(fp1);
fclose(fp1);
FILE *fp2;
fp2 = fopen(file2,"r");
function2(fp1);
fclose(fp2);
So what I found out is: since fp1 is closed, the code will automatically use the next open/linked pointer, in this case, is fp2. However, if the code is changed to
FILE *fp1;
//fp1 = fopen(file1,"r");
//function1(fp1);
fclose(fp1);
FILE *fp2;
fp2 = fopen(file2,"r");
function2(fp1);
fclose(fp2);
There will be segmentation fault. In addition, if there is an open file pointer fp3 in between fp1 and fp2, and fp1 is closed, the code will select fp3.
I am not sure this way of C dealing with deleted/closed FILE pointer is just a language specific fail-safe mechanism, or has something to do with the way these pointer variables lie in the physical memory? And what happens to these pointers after fclose()?
eg. If all FILE pointers are stored consecutively in memory and fclose only delete the memory the current pointer uses, then C will access the next available memory chunk to get the value.
PS: I am not sure if all FILE pointers are stored separately from other variables so I tested it by inserting a new int pointer assignment between the above fp1 and fp2 segments. It does not interfere with the FILE pointer "inherit" process. So probably the FILE pointers are stored separately?
eg. However, if flcose() make the current pointer a NULL pointer, should any command using the current pointer just produce an error?
Thank you!
Performing any action on the
FILE
pointed to byfp1
after callingfclose
on it results in Undefined Behavior. In all likelihood, what's happening is that, since the memory pointed to byfp1
was freed for reuse,fp2
happens to have the same value thatfp1
had prior to it becoming invalid, and thus when the implementation dereferencesfp1
, it accesses the memory pointed to byfp2
.