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?