Sil*_*Rab 4 c string malloc free pointers
因此,我不断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;
}
Run Code Online (Sandbox Code Playgroud)
如果有帮助,则可以const char*采用以下形式:
方法
SP request-target SP HTTP-version CRLF
其中SP是一个空格,CRLF是墨盒返回,换行。
更改此:
char* copy = malloc(sizeof(line));
Run Code Online (Sandbox Code Playgroud)
对此:
char* copy = malloc(strlen(line) + 1);
Run Code Online (Sandbox Code Playgroud)
第一个为linePOINT 的大小分配空间,即POINTER!
第二个为NULL终止符分配的空间等于指向该字符串的字符串的长度line,再加上一个(请记住,您将拥有更幸福的c -life)!;)
顺便说一句,我认为将代码的注释写在代码行上方(而不是在代码行旁边)更为常见。:)