我正在为一项任务实现 tail。我让它正常工作,但我似乎在随机时间从 free 中收到错误。
我看不到,要将其追踪到一个模式或除此之外的任何东西都是一致的。
例如,如果我将我的程序称为“tail -24 test.in”,我将在多次运行的同一行中得到错误校验和错误。但是,如果有不同的文件甚至不同的行数要打印回来,我会毫无错误地返回。
关于如何追踪问题的任何想法,我已经尝试调试了几个小时但无济于事。
这是有问题的代码:
lines 被定义为一个 char** 并且被 malloc 为:
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;
}
最佳答案
您的例程正在写入超出分配的行缓冲区。
作为参数传递的行的大小(即“len”)可能不包括 NUL 终止符。当您调用 malloc 复制行(即“s”)时,您需要为字符串终止符分配一个额外的字节:
*(lines + slot) = (char *) malloc((len + 1) * sizeof(char));
关于c - 分配错误 : incorrect checksum for freed object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/232678/