我的fread程序有什么问题?

时间:2012-02-05 03:01:36

标签: c malloc free fread file-read

我正在从二进制文件中读取内容。如果我将数据元素作为char读入我没有得到任何malloc错误,但如果我读入任何其他数据类型,比如short或int,程序成功读取字节但是当我 free 我得到的指针这可能是由于堆的损坏。有人能告诉我我在做什么错吗?

代码:

#include <stdio.h>
#include <stdlib.h>

#define TYPE int //char or short

int main () {
  FILE * pFile;
  long lSize;
  TYPE * buffer;
  size_t result;

  pFile = fopen ( "4.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 = (TYPE*) malloc (lSize/sizeof(TYPE));
  if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}

  // copy the file into the buffer:
  result = fread (buffer,sizeof(TYPE),lSize/sizeof(TYPE),pFile);
  if (result != lSize/sizeof(TYPE)) {fputs ("Reading error",stderr); exit (3);}
  perror("This is the problem: ");
  /* the whole file is now loaded in the memory buffer. */

  // terminate
  fclose (pFile);
  free (buffer);              // free causes heap related issue
  return 0;
}

1 个答案:

答案 0 :(得分:1)

malloc将字节大小作为参数,因此行

buffer = (TYPE*) malloc (lSize/sizeof(TYPE));

应该阅读

buffer = (TYPE*) malloc (lSize);