1

I'm writing a function where I manipulate a string and return a string malloc'd after a series of strcpy and strcat:

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;
}

and then I free the returned pointer in the caller's code:

  ...

  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);

  ...

I think to correctly free that memory but Valgrind still says that this memory is not freed and is consequently lost. What's wrong with that code?? Thanks for the help!

4

2 回答 2

3

第二次调用分配的内存doRequest()永远不会是free()d。

我建议替换这一行:

printf("Return message: %s\n", doRequest(command, headers, body));

这样:

printf("Return message: '%s'\n", reply);
于 2013-09-02T16:40:00.517 回答
2

printf("返回消息:%s\n", doRequest(command, headers, body));

没有free()那个 doRequest 调用。你的意思是printf(..., reply),也许?

此外,没有边界检查的 strcpy + strcat 是确保(可利用)缓冲区溢出的可靠方法。

于 2013-09-02T16:41:10.587 回答