I have a hard time understanding the difference between these three:
const char * f() {
return "this is a test";
}
const char * g() {
const char * str = "test again";
return str;
}
const double * h() {
const double a = 2.718;
return &a;
}
I get a warning for the h(), as warning: address of local variable ‘a’ returned. Which makes sense, but I do not understand why the compiler (gcc -Wall) is ok with the f() and g() function.
- Isn’t there a local variable there?
- When and how does the pointer returned by
f()org()gets deallocated?
String literals are not stored in the local stack frame. They live in a fixed place in your executable. Contrast:
with
In the former, the return value points to a fixed place in your executable. In the latter, the return value points to (a now invalid location in) the stack.