【发布时间】:2017-09-30 03:29:13
【问题描述】:
我收到此错误:
`./sorter' 中的错误:双重释放或损坏 (!prev):0x0000000000685010
然后是一堆数字,这是内存映射。 我的程序从标准输入读取电影及其属性的 CSV 文件并将其标记化。带有逗号的电影标题用引号括起来,所以我将每一行分成 3 个标记,并使用逗号作为分隔符再次标记前后标记。我在代码末尾释放了所有的 malloc,但仍然出现此错误。 csv 被扫描到最后,但我收到一条错误消息。如果我根本不释放 malloc,我不会收到错误消息,但我非常怀疑它是否正确。这是我的 main() :
char* CSV = (char*)malloc(sizeof(char)*500);
char* fronttoken = (char*)malloc(sizeof(char)*500);
char* token = (char*)malloc(sizeof(char)*500);
char* backtoken = (char*)malloc(sizeof(char)*500);
char* title = (char*)malloc(sizeof(char)*100);
while(fgets(CSV, sizeof(CSV)*500,stdin))
{
fronttoken = strtok(CSV, "\""); //store token until first quote, if no quote, store whole line
title = strtok(NULL,"\""); //store token after first quote until 2nd quote
if(title != NULL) //if quotes in line, consume comma meant to delim title
{
token = strtok(NULL, ","); //eat comma
}
backtoken = strtok(NULL,"\n"); //tokenize from second quote to \n character (remainder of line)
printf("Front : %s\nTitle: %s\nBack: %s\n", fronttoken, title, backtoken); //temp print statement to see front,back,title components
token = strtok(fronttoken, ","); //tokenizing front using comma delim
while (token != NULL)
{
printf("%s\n", token);
token = strtok(NULL, ",");
}
if (title != NULL) //print if there is a title with comma
{
printf("%s\n",title);
}
token = strtok(backtoken,","); //tokenizing back using comma delim
while (token != NULL)
{
printf("%s\n", token);
token = strtok(NULL, ",");
}
}
free(CSV);
free(token);
free(fronttoken);
free(backtoken);
free(title);
return 0;
【问题讨论】:
-
while(fgets(CSV, sizeof(CSV)*500,stdin))-->while(fgets(CSV, sizeof(*CSV)*500,stdin)) -
strtok不分配内存,你不应该释放它返回的所有指针。 -
除了@Jack 所说的之外,一旦您将
strtok的输出分配给指针,您使用malloc创建的内存就会泄漏,因为您不再有指向它的指针来释放它。 -
malloc的返回不用强制转换,没必要。见:Do I cast the result of malloc? -
你脑子里有 sizeof...
char *CSV = malloc(500); fgets(CSV, 500, stdin);
标签: c string memory-management malloc free