0

When I go to compile my program I get the error: address of stack memory associated with local variable 'indexphp' returned. I think the problem is that indexphp is stored in the stack so I tried to make indexphp a static char array but that gave me more errors. How would I declare indexphp and indexhtml on the heap instead of the stack?

Here is my code:

char* indexes(const char* path)
{
// sub-strings used to check
char* php  = "index.php";
char* html = "index.html";

// char arrays used to store return value
char indexphp[strlen(path) + strlen(php)];
char indexhtml[strlen(path) + strlen(html)];

if (strstr(path, php) != NULL)
{
    // assigns path and php to indexphp
    for (int i = 0, m = 0; i < strlen(path) + strlen(php); i++)
    {
        if (i < strlen(path))
        {
            indexphp[i] = path[i];
        }
        else
        {
            indexphp[i] = php[m];
            m++;
        }
    }
    return indexphp;
}
else if (strstr(path, html) != NULL)
{
    // assigns path and html to indexhtml
    for (int j = 0, k = 0; j <strlen(path) + strlen(html); j++)
    {
        if (j < strlen(path))
        {
            indexhtml[j] = path[j];
        }
        else
        {
            indexhtml[j] = html[k];
            k++;
        }
    }
    return indexhtml;
}
return NULL;
}
0
0

I can not explain the error any better than the several explanations you can find here or here. I would add that since indexes is expecting a char* as it's return value, that you should return a char*. That is also emphasised in the instructions here:

this function should dynamically allocate memory on the heap for the returned string.

To clarify the instructions a bit. This

the function, given a /path/to/a/directory, returns /path/to/a/directory/index.php if index.php actually exists therein,

doesn't mean "does index.php exist in the path argument received by the function". That's what this test if (strstr(path, php) != NULL) would detect.

Rather it means: function recieves path argument (something like /home/ubuntu/workspace/pset6/public). Is there a file named 'index.php' in that path? One of the handy dandy functions you should investigate is access. You'll also want to check out strcpy and strcat for writing this function.

You must log in to answer this question.

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