我在编写 C 代码时经常使用网站 www.cplusplus.com 作为引用。
我正在阅读 fread 页面上引用的示例并有一个问题。
作为他们发布的示例:
/* fread example: read a complete file */
#include <stdio.h>
#include <stdlib.h>
int main () {
FILE * pFile;
long lSize;
char * buffer;
size_t result;
pFile = fopen ( "myfile.bin" , "rb" );
if (pFile==NULL) {fputs ("File error",stderr); exit (1);}
// obtain file size:
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);
// allocate memory to contain the whole file:
buffer = (char*) malloc (sizeof(char)*lSize);
if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
// copy the file into the buffer:
result = fread (buffer,1,lSize,pFile);
if (result != lSize) {fputs ("Reading error",stderr); exit (3);}
/* the whole file is now loaded in the memory buffer. */
// terminate
fclose (pFile);
free (buffer);
return 0;
}
在我看来,如果 result != lSize,则永远不会调用 free(buffer)。在这个例子中这会是内存泄漏吗?
我一直认为他们网站上的示例质量很高。可能是我理解的不正确?
最佳答案
在这个例子中不会是内存泄漏,因为终止程序(通过调用 exit()
)会释放与其关联的所有内存。
但是,如果您将这段代码用作子例程并调用诸如 return 1;
之类的东西来代替 exit()
,则会发生内存泄漏。
关于c - 来自 C++ Reference 的 fread 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/493650/