c - 来自 C++ Reference 的 fread 示例

标签 c fread

我在编写 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/

相关文章:

c++ - 如何从文件中读取前 256 位并将它们存储在两个数组中

c++ - VSS 备份的正确流程 - VSS_E_BAD_STATE 错误

c - gcc: __fread_chk_warn 警告

c - C语言读取文本文件的问题

c - Scanf 正在获取垃圾文件

无法将缓冲区的内容复制到 C 中的字符串 : reading from . bin 文件中

c - 写入和读取链表

c - 如何检测内存泄漏?

c - 在C中,我想连续打印4个十进制数,然后打印接下来的4个

c - 有什么不好的代码吗? (C 上的快速排序时间复杂度)