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!