0

Here is my implementation of the indexes function in pset6:

char* indexes(const char* path)
{
    char* php = "index.php";
    char* html = "index.html";

    char* pathCopy = malloc(strlen(path) + strlen(html) + 1);
    if (pathCopy == NULL)
    {
        printf("Could not check index - insufficient memory\n");
        return NULL;
    }

    strcpy(pathCopy, path);
    strcat(pathCopy, php);
    if (access(pathCopy, F_OK) != -1)
        return pathCopy;

    strcpy(pathCopy, path);
    strcat(pathCopy, html);
    if (access(pathCopy, F_OK) != -1)
        return pathCopy;

    return NULL;
}

I'm struggling with how to free the memory allocated for pathCopy. I need to return the pointer to main, so it seems I can't call free within indexes. But every place I've tried to insert a free call in main (onto the value "index", which is how indexes returns it), it either does nothing at all or breaks the functionality of indexes. Valgrind returns the same single leak no matter what.

Am I barking up the wrong tree? Is there something simple I'm missing? Everything else in the file is working smoothly, both locally and as per check50.

1 Answer 1

1

Does valgrind return the leak if it finds index.html or index.php? I would predict this indexes would leak memory only if neither of those files is "found". Generally speaking, one would not change anything about "main" for this assignment, so adding a free to main is not the right approach. Since the memory for pathCopy is allocated in the indexes function, it needs to be free'd in the indexes function. But when? When you do not return a pointer to that allocated memory to main.

2
  • That was it! Thanks very much. As a general rule, do I need to worry about memory allocated within functions if I'm returning a pointer? (i.e., is the memory I allocated being freed through some specific action in main, or is that just how it goes when allocating memory within a function?)
    – WillF
    Commented Nov 2, 2016 at 17:25
  • The specific rule is: anything that is malloc'd must be freed, so, no, this is not how it goes when allocating memory within a function. server basically lives in the while loop at line 130 until it receives a quit signal (^C). The memory allocated by indexes is free'd at line 135 in server.c (assuming I've read it correctly :). Notice how index is used upon return from the indexes function. Commented Nov 2, 2016 at 17:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .