tags:

views:

133

answers:

3

Hi,

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!

+2  A: 

"Hello" is a constant. It does not disappear so it is OK to use the pointer. A local variable is another story...

Arve
+3  A: 

String literals are allocated statically, so returning the address of a string literal like "HELLO" is safe, and it can be used outside the function without any problems.

Jerry Coffin
+3  A: 

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).

jamesdlin