gpt4 book ai didi

c - 免费(): invalid next size (fast) error

转载 作者:太空狗 更新时间:2023-10-29 15:23:32 24 4
gpt4 key购买 nike

所以当我运行我的代码时,我一直遇到这个错误:free(): invalid next size(fast)。如果我删除函数末尾的 free,我知道我正在泄漏内存,但我不明白为什么会出现此错误。

我认为这与我错误地分配内存有关,但我似乎找不到解决方法,这是我的代码:

bool parse(const char* line) //NOT WORKING JUST QUITE 
{
char* copy = malloc(sizeof(line)); //allocate space for a copy of the line parameter
strcpy(copy, line); //copy the line parameter

char* method = strtok(copy, " "); //pointer to the method
char* reqLine = strtok(NULL, " "); //pointer to the requestline
char* version = strtok(NULL, "\r\n"); //pointer to the HTTP-Version

if (strcmp(method,"GET") != 0) //if the method is not GET
{
printf("%s\n", method);
printf("ERROR 405\n");
return false;
}
if (strncmp(reqLine, "/", 1) != 0)//if the request line does not begin with a / character
{
printf("%c\n", reqLine[0]);
printf("%s\n", reqLine);
printf("ERROR 501\n");
return false;
}
if (strchr(reqLine, 34) != NULL) //if the request line contains a " character
{
printf("%s\n", reqLine);
printf("ERROR 400\n");
return false;
}
if (strcmp(version, "HTTP/1.1") != 0)
{
printf("%s", version);
printf("ERROR 505\n");
return false;
}

//free(copy);
return true;
}

如果有帮助,传入的 const char* 行的形式为:

method SP request-target SP HTTP-version CRLF

其中SP为空格,CRLF为回车换行。

最佳答案

改变这个:

char* copy = malloc(sizeof(line));

为此:

char* copy = malloc(strlen(line) + 1);

第一个为line的大小分配空间,这是一个POINTER!

而第二个,分配空间等于 line 指向的字符串的长度,加一,用于 NULL 终止符(请不要忘记和你会过上更幸福的生活 -生活)! ;)


顺便说一句,我认为将代码注释写在代码行上方(而不是旁边)更为常见。 :)

关于c - 免费(): invalid next size (fast) error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39113727/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com