Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Malloc Error: incorrect checksum for freed object

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;
}
like image 300
None Avatar asked Feb 03 '23 12:02

None


1 Answers

Your routine is writing beyond the allocated line buffer.

The size of the line passed as an argument (i.e. "len") probably does not include the NUL terminator. When you call malloc to copy the line (i.e. "s") you need to allocate an extra byte for the string terminator:

 *(lines + slot) = (char *) malloc((len + 1) * sizeof(char));
like image 171
JayG Avatar answered Feb 06 '23 11:02

JayG