我正在编写一个函数,我操作一个字符串并在一系列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仍然说这个内存没有被释放,因此丢失了。这段代码出了什么问题? 谢谢你的帮助!
答案 0 :(得分:3)
第二次拨打doRequest()
时分配的内存永远不会是free()
d。
我建议更换这一行:
printf("Return message: %s\n", doRequest(command, headers, body));
由此:
printf("Return message: '%s'\n", reply);
答案 1 :(得分:2)
printf(“返回消息:%s \ n”,doRequest(命令,标题,正文));
该doRequest调用没有free()
。您的意思是printf(..., reply)
,也许?
另外,没有边界检查的strcpy + strcat是一种可以利用(可利用的)缓冲区溢出的方法。