【发布时间】:2016-08-24 03:01:16
【问题描述】:
所以当我运行我的代码时,我一直运行到这个错误: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* 行格式为:
方法
SP request-target SP HTTP-version CRLF
其中 SP 是空格,CRLF 是回车换行。
【问题讨论】:
-
你在某处分配内存。然后你写出那个记忆的界限。这是导致此类错误的唯一原因。
-
我不认为这是@JoachimPileborg 的情况,我发布了一个答案。我认为他的
malloc()不是应有的样子! -
另外,当你有一个指针时,那个指针上的
sizeof会给你指针的大小,而不是它指向的大小。在 32 位系统上,它很可能是4,而在 64 位系统上,它很可能是8。 -
@gsamaras 这正是原因。分配太小,OP 写入超出分配范围。
-
我以为这就是为什么会有
strdup?
标签: c string pointers malloc free