I'm nearing the end of this pset, having successfully implemented both parse and lookup. I've already had one attempt at load and, thinking it was correct (it is not), moved onto index; in the process of writing and testing this I came across this error:
*** Error in `./server': malloc(): memory corruption: 0x0000000001809ad0 ***
Aborted
The error occurs in the block below:
void transfer(const char* path, const char* type)
{
// ensure path is readable
if (access(path, R_OK) == -1)
{
error(403);
return;
}
// open file
FILE* file = fopen(path, "r");
if (file == NULL)
{
error(500);
return;
}
After debugging/using GDB, I found it occurs specifically on the line:
FILE* file = fopen(path, "r");
After some searching on google and stack exchange, I found the issue seems to come from potential overflow of allocated memory or something similar. Since the 'index' function is the only place where I have allocated memory by this point, I believe the error to stem from it. This is my index function at the moment:
char* indexes(const char* path)
{
// open directory
DIR* dir = opendir(path);
// store all the files in namelist
struct dirent** namelist = NULL;
int n = scandir(path, &namelist, NULL, alphasort);
for (int i = 0; i < n; i++)
{
// print out current entry for debugging purposes
printf("Current directory item = %s\n", namelist[i]->d_name);
if (strcmp(namelist[i]->d_name, "index.php") == 0)
{
// allocate enough memory to store string and terminator
char* index = NULL;
index = calloc(1, sizeof(path) + 10);
// copy path into allocated memory and add file name onto the end
strcpy(index, path);
strcat(index, "index.php");
// free allocated memory and close directory
freedir(namelist, n);
closedir(dir);
return index;
}
else if (strcmp(namelist[i]->d_name, "index.html") == 0)
{
// allocate memory
char* index = NULL;
index = calloc(1, sizeof(path) + 11);
// copy and concatenate strings
strcpy(index, path);
strcat(index, "index.html");
freedir(namelist, n);
closedir(dir);
return index;
}
}
freedir(namelist, n);
closedir(dir);
// index files not found
return NULL;
}
I'm aware a bit of error checking is missing and lots of code is copied and pasted, but at the moment I'm trying to nail the core functionality before cleaning it up. So my question is, does anyone know why I'm getting this error?
Thanks in advance for any help!