Alex Rivera | Logout

Malloc Error: incorrect checksum for freed object

Asked 2008-10-24T06:53:08.220
9

I am working on implementing tail for an assignment. I have it working correctly however I seem to be getting an error from free at random times.

I can't see, to track it down to a pattern or anything besides it is consistent.

For example if I call my program as "tail -24 test.in" I would get the the the incorrect checksum error at the same line on multiple runs. However, with different files and even different numbers of lines to print back I will come back without errors.

Any idea on how to track down the issue, I've been trying to debug it for hours to no avail.

Here is the offending code:

lines is defined as a char** and was malloc as:

lines = (char**) malloc(nlines * sizeof(char *));

void insert_line(char *s, int len){

  printf("\t\tLine Number: %d Putting a %d line into slot: %d\n",processed,len,slot);
  if(processed > numlines -1){//clean up
    free(*(lines+slot));
    *(lines + slot) = NULL;
  }
  *(lines + slot) = (char *) malloc(len * sizeof(char));
  if(*(lines + slot) == NULL) exit(EXIT_FAILURE);
  strcpy(*(lines+slot),s);
  slot = ++processed % numlines;
}
Edit
Report

1 Answer

4

If you can consistently reproduce the problem with specific input parameters, you should debug like this:

  • First debug to the precise free that causes the problem.
  • Then figure out when the memory that is about to be free'd was malloc'ed.
  • Next, debug to the place where the memory is malloc'ed.
  • Locate in the memory viewer the allocated block of memory. Note both the start and end of the block. There is probably a special value called a guard block just before and just after the block.
  • Now step through the code until the memory is free'd. At some point your code should mistakenly overwrite the guard block. That is the offending statement.

Note that the problem might very well be in a completely different part of your program. Even though it is this free that is reporting the error, the code that overwrites the guard block can be anywhere.

answered 2008-10-24T07:32:39.793

Your Answer