简体   繁体   中英

Why and how returning the address of a static variable is OK while doing the same with non-static variable gives wrong result?

char str[] = "hello";

This definition dosn't work but

static char str[] = "hello" 

This works, why?

Full code:

char *retstr(void)
    {
        char str[] = "hello"; //This definition dosnt work
        return str;
    }

    int main()
    {
        printf("\n%s\n",retstr());
        return 0;
    }

In case of

 char str[] = "hello"; //This definition dosnt work

you're trying to return the address of a local variable str . Using the returned value is undefined behaviour here, because once the retstr() function finishes execution, there is no existence of the str variable.

OTOH,

 static char str[] = "hello";

works, because, the static variable as static storage duration . Its lifetime is the entire execution of the program. So even after the retstr() function finishes execution, str remains valid, and hence, the return value is valid to be used.

Related: C11 , chapter §6.2.4, Storage durations of objects , Paragraph 3

... with the storage-class specifier static , has static storage duration . Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.

char str[] = "hello"; //This definition dosnt work
return str;

Here you are returning the local address. that's why it is not working

static char str[] = "hello" 

while in this one, you are changing the scope of the 'str' variable to the whole program. that's why it works.

You cannot return local variables from a function. Local variables live on the stack, and once the function completes, that stack space is released and can be used by the next function call.

char str[] = "hello"; //this won't work as it is a local variable

Once you come out of the scope there doesn't exist any variable named str for other function calls.

But static variable lifetime extends across the entire run of the program.

static char str[] = "hello"; //this will work

Hence on using static it is not giving any error.

Static variables are created once and does not get destroyed when a function returns but local variables gets destroyed once our function ends.
local variable are created every time a function is called and gets destroyed when it returns.

In case of local variable : you are returning a pointer to a string which exists no-more.
In case of global variable : the string is still there and hence it will always work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM