user1190135
user1190135

Reputation: 225

What is wrong with my fread program?

I'm reading contents from a binary file. If I read in data elements as char I don't get any malloc errors, but if I read in as any other data types, say short or int, the program successfully reads in the bytes but when I free the pointer I get This may be due to a corruption of the heap. Can someone tell me what wrong I'm doing?

The code:

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

Upvotes: 1

Views: 1837

Answers (1)

Greg Inozemtsev
Greg Inozemtsev

Reputation: 4671

malloc takes a size in bytes as a parameter, so the line

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

should read

buffer = (TYPE*) malloc (lSize);

Upvotes: 1

Related Questions