简体   繁体   中英

I cannot return pointer to local variable, but I can return pointer to data of local struct in c?

I know returning pointer to local variable is not a good idea, because the stack used for that variable will be reused. As so:

#include <stdio.h>

int *func(){
    int x = 10;
    return &x;
}

int main(){
    printf("%p\n",(void*)func());
}

print (nil) as expected.

However, why can I then return pointer to data of local struct? :

#include <stdio.h>

struct foo{
    char c;
    int *p;
};

int *func(){
    struct foo f;
    f.c = 'c';
    
    int local = 10;
    f.p = &local;
    return f.p;
}

int main(){
    int *b = func();
    printf("%d\n",*b);
}

The struct foo f is local in function func so there should be the same rule for every local variable - that is automatic storage in stack. I have not yet looked at assembler output of it to confirm that, but if this assumption is not true, then why is there special treating for struct types? Before I look to asm, is the storage of struct foo in stack?

All of your examples cause undefined behaviour . The address of an object that no longer exists is an indeterminate value (C11 6.2.4/2) and trying to print an indeterminate value causes undefined behaviour.

See this question for more Standard references and discussion about the use of indeterminate values and rationale for the language rules.

Being undefined behaviour, you should not expect any particular behaviour, such as nil or otherwise.

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