When memory is allocated in a function, isn’t it impossible to use that memory outside the function by returning its address?
Are there exceptions? It seems the following is such an “example”:
const char * f() {
return "HELLO";
}
How to explain it?
Thanks!
Why do you think it’s impossible? It sounds like you’re confusing it with the rule about not returning addresses to local variables to calling functions. You can’t do that because variables local to a function have a lifetime only for the duration of that function call; once the function returns, those variables become garbage.
There are things that have lifetimes that extend beyond the lifetime of the function call; it’s okay to return addresses to them. Examples of these things are blocks of memory allocated on the heap (e.g. with
malloc) or are things that have static storage duration (e.g. global variables and string literals).