Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Warning: Function returns address of local variable

Tags:

c

pointers

malloc

The function below takes the argv[0] argument that contains the calling path of the application and replaces the last bit until it hits a "/" with the name of the new app I want to spawn that sits in the same folder.

BTW: I'm declaring a global argv variable so the function can have access to it because I did not want to pass the info in every function call.

When I compile my code, all seems to work, but I get the above warning.

I know that I'm declaring the variable and that as soon as the function returns it will be destroyed.

Being a beginner C programmer I wanted to know what the most elegant/easiest way of solving this problem would be?

Should I pass a pointer to the function or malloc some memory?

char *returnFullPath()
{
    char pathToApp[strlen(argv[0])+1];
    strcpy(pathToApp, argv[0]);
    int path_length = strlen(argv[0]);

    while (pathToApp[path_length] != '/')
    {
        path_length--;
    }

    if (path_length > 2)
        pathToApp[path_length+1] = '\0';
    else
        pathToApp[0] = '\0';

    // length of getcwd + length of pathtoapp + 1 for zero plus 6 for "bidbot"
    char bidbotPath[strlen(getcwd(NULL,0)) + strlen(pathToApp) + 1 + 6];

    sprintf(bidbotPath, "%s/%sbidbot", getcwd(NULL,0), pathToApp);

    return bidbotPath;
}
like image 424
Frank Vilea Avatar asked Aug 01 '11 11:08

Frank Vilea


2 Answers

Some other answers suggest that you malloc something and return it. This is bad practice in the same sense as in C++, when you new something in a function and the caller is supposed to delete it (who has ownership?)

There is a reason that many C APIs have the format of:

function(buf, length);

Meaning that the CALLER supplies the buffer and how long it is. IT is the caller's responsibility to allocate and de-allocate this buffer and your function should use it, and check that you're not going to overflow the length.

Do not malloc and return. It's just asking for trouble.

like image 131
Moo-Juice Avatar answered Oct 05 '22 06:10

Moo-Juice


Replace

char bidbotPath[strlen(getcwd(NULL,0)) + strlen(pathToApp) + 1 + 6];

with

char* bidbotPath = malloc(strlen(getcwd(NULL,0)) + strlen(pathToApp) + 1 + 6);

That way your variable is allocated on the heap and not on the stack, so it will not be deleted after the function returns.

like image 41
Luchian Grigore Avatar answered Oct 05 '22 06:10

Luchian Grigore