我正在编写一个函数,我在其中操作一个字符串并在一系列 strcpy 和 strcat 之后返回一个 malloc 的字符串:
char * doRequest(char *start, char**headers, char *body)
{
char * reply;
char * com;
int i;
reply = malloc(512 * sizeof(char));
if (!reply)
return SRV_ERR;
strcpy(reply, "Your request ");
com = strtok(start, " ");
strcat(reply, com);
strcat(reply, " with options: ");
for (i = 0; headers[i] != NULL; i = i + 2)
{
strcat(reply, headers[i]);
strcat(reply, ", ");
}
strcat(reply, "has been received.");
strcat(reply, "\0");
return reply;
}
然后我在调用者的代码中释放返回的指针:
...
char * reply = doRequest(command, headers, body);
int len = strlen(reply);
printf("Return message: %s\n", doRequest(command, headers, body));
if(writen(s, reply, len) != len) printf("Write error while replying\n");
else printf("Request served correctly.\n");
free(reply);
...
我想正确地释放该内存,但 Valgrind 仍然说该内存未释放并因此丢失。那个代码有什么问题?? 感谢您的帮助!
最佳答案
第二次调用 doRequest()
分配的内存永远不会是 free()
d。
我建议替换这一行:
printf("Return message: %s\n", doRequest(command, headers, body));
通过这个:
printf("Return message: '%s'\n", reply);
关于c - 返回字符串的内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18577566/