简体   繁体   中英

Memory leak with a returned string

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!

The memory allocated by the second call to doRequest() is never free() d.

I'd propose to replace this line:

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

by this:

printf("Return message: '%s'\n", reply);

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

No free() for that doRequest call. Did you mean printf(..., reply) , maybe?

Also, strcpy + strcat without bounds checking is a sure way to have (exploitable) buffer overflows.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM