Valgrind output:
GET /cs3157/tng/index.html
==760== Invalid read of size 1
==760== at 0x4C2E7D4: strstr (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==760== by 0x400E67: HandleTCPClient (http-server.c:101)
==760== by 0x400D42: main (http-server.c:75)
==760== Address 0x0 is not stack'd, malloc'd or (recently) free'd
Relevant code:
FILE *input = fdopen(clntSocket, "r"); //socket wrapped with FILE *
if (input == NULL)
{
perror("fdopen failed");
fclose(input);
return;
}
char request_buffer[100];
char out_buf[BUF_SIZE];
int len, res;
while( fgets(request_buffer, sizeof(request_buffer),input) != NULL)
{
request_buffer[sizeof(request_buffer)-1] = '\0'; //null terminates buffer
char *request = request_buffer;
char *token_separators = "\t \r\n"; // tab, space, new line
char *method = strtok(request, token_separators);
char *requestURI = strtok(NULL, token_separators);
char *httpVersion = strtok(NULL, token_separators);
if( strstr(method,"GET") != NULL )
{
if( requestURI[strlen(requestURI)] == '/' )
requestURI = strcat(requestURI,"index.html");
printf("%s %s\n", method, requestURI);
}
memset(request_buffer,'\0',sizeof(request_buffer) );
}
fclose(input); //close the socket by closing the FILE * wrapper
I read that this error is typically caused by failure to null terminate the String. I thought that my first line after fgets() would prevent that from being a problem. I'm guessing I'm overlooking something. I appreciate any help.
edit: Program ends crashes with a segmentation fault.
It sounds (from Valgrind's report) as if method
is NULL
. You should step through this code with a debugger to verify that the tokenizing works as intended.
Also, you should declare all those pointers as const char *
since they're not intended to be written to. This is of course a minor point, but I try to encourage use of const
whenever possible. :)