[pset6] server.c works for cat.jpg, but not other files
My server.c program is only working for cat.jpg at the moment. I believe the issue is my load function. At the home page:
- When I click cat.jpg, the cat image shows up properly.
- When I click cat.html, favicon.ico, hello.html, and test, I get a blank white screen.
- When I click hello.php, I get a segmentation fault.
Valgrind gave me this info when I clicked on hello.php and subsequently caused the seg fault:
==31541== Invalid read of size 1
==31541== at 0x4C31FC4: strstr (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==31541== by 0x403590: interpret (server.c:543)
==31541== by 0x401CA1: main (server.c:255)
==31541== Address 0x0 is not stack'd, malloc'd or (recently) free'd
==31541==
==31541==
==31541== Process terminating with default action of signal 11 (SIGSEGV)
==31541== Access not within mapped region at address 0x0
==31541== at 0x4C31FC4: strstr (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==31541== by 0x403590: interpret (server.c:543)
==31541== by 0x401CA1: main (server.c:255)
where line 542 and 543 in server.c are as follows:
char* haystack = content;
char* needle = strstr(haystack, "\r\n\r\n");
Here is my load function:
bool load(FILE* file, BYTE** content, size_t* length)
{
// initialize content and its length
*content = NULL;
*length = 0;
// initialize buffer
BYTE buffer[512];
// read from file and attempt to store 512 bytes in buffer
while (fread(buffer, 512, 1, file) != 0)
{
// append bytes to content
*content = realloc(*content, *length + 512 + 1);
if (*content == NULL)
{
printf("Memory allocation error.\n");
*length = 0;
return false;
}
memcpy(*content + *length, buffer, 512);
*length += 512;
// null-terminate message thus far
*(*content + *length) = '\0';
}
// if EOF reached
if (feof(file))
{
return true;
}
// if error occurred
else
{
if (*content != NULL)
{
free(*content);
*content = NULL;
}
*length = 0;
return false;
}
}
Can someone point me in the right direction? I've been stuck on this for a while and would appreciate some guidance. Thanks!
Posted Feb 22, 2016, 4:54 AM UTC · edited
16