Firstly, well done for using valgrind
.
At point 6, you do:
result = (void *) malloc (fs.st_size);
I suggest you do:
size_t sz = fs.st_size;
result = malloc (sz+1); /* no need to cast return of malloc() */
((char *)result)[sz] = 0; /* zero terminate it */
As the problem you have is that you have malloc
'd exactly sufficient room for the file and the body, but not the terminating NUL
.
Your terminate_string
idea is broken as that writes beyond the end of response_body
. If the response body is zero terminated you don't need that, so can drop it.
For a similar reason, you want:
char *response = malloc(sizeof(char) *
(strlen(response_header) + strlen(response_body) + 1));
+1
being for the NUL
.
However, there is a bigger problem: HTTP documents themselves can contain \0
, i.e. zero bytes, in which case you cannot strlen()
them. A better fix would therefore be to write
the response header, then write
the response body, and simply keep the size of the body around as an integer. I've explained what the problem is above as it's important you know.