Why does this code work and give the correct results?

I have two files, one called N.bin and the other called R.bin. After months of use, I only noticed that I have a bug. However, I thought this would cause a system crash. But at first he did not do this, and the second gave the correct result. Here is the code:

Please see line 19 for how I mistakenly switched from Nfile, 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); 

Please help me why this code works!

+4
source share
1 answer

Perhaps this is due to the way C runtime libraries handle memory allocation. fopen mallocs buffer since it returns a FILE * object. fclose frees the buffer. The subsequent fopen will be the malloc buffer of the same size as before, and just happened to return the same memory as the previous free . If you compare the values ​​of the pointer R and N, they will be the same.

Note that if you did the memory allocation \ deallocation between lines 11 and 14, the system would be broken. In addition, depending on how the debugger works and runtime, sometimes you can use the free function to not reuse freed memory.

To prevent a similar error in the future, always do this:

 fclose (handle); handle = 0; // so you get a null pointer error if you accidentally use it again 
+6
source

Source: https://habr.com/ru/post/1369144/


All Articles