I have two files, one is called N.bin and the other is called R.bin. After couple of months of using it, I just noticed that I have a mistake there. However, I thought the system would crash because of it. But first it didn’t and second it gives the correct result. Here is the code:
Please see Line 19 how I mistakenly streamed in from Nfile and not Rfile .
// Read file N
1 long world_features_lSize;
2 FILE* NFile;
3 double* N;
4 NFile=fopen("N.bin","r+b");
5
6 fseek (NFile , 0 , SEEK_END);
7 lSize = ftell (NFile);
8 fseek (NFile , 0 , SEEK_SET);
9 N = (double*) malloc (sizeof(double)*lSize);
10 result = fread (N,1,lSize,NFile);
11 fclose(NFile);
////////////////// Read R
12 FILE* RFile;
13 double* R;
14 RFile=fopen("R.bin","r+b");
15 fseek (RFile , 0 , SEEK_END);
16 lSize = ftell (RFile);
17 fseek (RFile , 0 , SEEK_SET);
18 R = (double*) malloc (sizeof(double)*lSize);
19 result = fread (R,1,lSize,NFile);
20 fclose(RFile);
Kindly advice me why does this code work !!
This is probably down to the way the C run time libraries handle memory allocation.
fopenmallocs a buffer since it returns aFILE *object.fclosefrees the buffer. The subsequentfopenwill malloc a buffer the same size as before and it just happened to return the same memory the previousfreereleased. If you compare the pointer values of R and N they will be the same.Note that if you had done any memory allocation \ freeing between lines 11 and 14, then the system would have crashed. Also, depending on how the debugger works and the run time, the
freefunction can sometimes be made to not reuse the freed memory.To prevent this sort of bug in the future, always do this: