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;
}
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With