4

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 !!

Cassio
  • 2,912
  • 2
  • 20
  • 21
Louis
  • 1,265
  • 1
  • 15
  • 22
  • 2
    `RFile` ended up being stored the same place as `NFile` for whatever reason (or the same file descriptor or whatever is used). – user786653 Aug 26 '11 at 12:04
  • Probably N and R share the same Filedescriptor since you closed NFile freeing it's descriptor and when opening RFile the os just gave you the same descriptor but for a different file. I'm assuming you are on a *NIX platform. – RedX Aug 26 '11 at 12:08

1 Answers1

6

This is probably down to the way the C run time libraries handle memory allocation. fopen mallocs a buffer since it returns a FILE * object. fclose frees the buffer. The subsequent fopen will malloc a buffer the same size as before and it just happened to return the same memory the previous free released. 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 free function can sometimes be made to not reuse the freed memory.

To prevent this sort of bug in the future, always do this:

fclose (handle);
handle = 0; // so you get a null pointer error if you accidentally use it again
Skizz
  • 69,698
  • 10
  • 71
  • 108