[英]Memory leak with a returned string
我正在编写一个函数,该函数在处理一系列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);
printf(“返回消息:%s \\ n”,doRequest(命令,标头,正文));
该doRequest调用没有free()
。 您是说printf(..., reply)
,也许吗?
同样,不带边界检查的strcpy + strcat是确保(可利用的)缓冲区溢出的肯定方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.