Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
861 views
in Technique[技术] by (71.8m points)

pointers - C Warning: Function returns address of local variable

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] = '';
    else
        pathToApp[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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...