1

バイナリファイルからコンテンツを読み取っています。データ要素をcharとして読み込んだ場合、mallocエラーは発生しませんが、shortやintなどの他のデータ型として読み込んだ場合、プログラムはバイトを正常に読み込みますが、ポインターを解放すると、次のようになります。ヒープの破損が原因である可能性があります。誰かが私が何をしているのか教えてもらえますか?

コード:

#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;
}
4

1 に答える 1

1

mallocパラメータとしてバイト単位のサイズを取るため、行

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

読むべき

buffer = (TYPE*) malloc (lSize);
于 2012-02-05T03:08:20.560 に答える