Here is the code,
char *foo()
{
static char s[10] = "abcde";
return s;
}
char *bar()
{
char *c = foo();
return c;
}
int main()
{
printf("%s\n", bar());
}
Typically, it is wrong to return a local pointer as I did in bar, but now c points to a static var returned by foo, would it be correct to return a local var c in bar?
I tried, it printf the right value, but I don’t understand how it works. I thought, when bar() finishes, the var c should vanish, which should make printf print undefined stuff, right?
Follow Up
char *c is a local var, if char *c = "abcde";, I assume this: c is a local var which resides in the function’s stack, while "abcde" is a constant var which resides in the constants-area (part of the heap?), so when bar() finishes, c vanishes, but "abcde" still remains in the heap, right?
Variable
cis only a pointer. It is not wrong to return a local pointer from a function, you do it all the time. For example, when you store a result ofmallocin a pointer, the pointer is local, but the storage it points to is not. It is, however, wrong to return a pointer to a local storage. Since in your examplecnever points to a locally allocated data, your code works correctly as written.EDIT (in response to the Follow Up)
The constants area is not usually part of the heap, it is either a separate arrea, usually adjacent to the area where the machine code of your program is stored.
“abcde” remains in the constants area, not in the heap, but the concept is correct: the pointer to that constant remains valid throughout the entire run-time of your program.