-3
char* f()
{
char s[100];
//....function body code
return s;
}

Why should it not be written like this?

djechlin
  • 59,258
  • 35
  • 162
  • 290
  • 2
    Because program go poof! – Hot Licks May 21 '13 at 21:53
  • Someone please find the dupe. – djechlin May 21 '13 at 21:53
  • 1
    Hey!! Let's be polite, now. – Hot Licks May 21 '13 at 21:54
  • When you call a function, all of the variables declared "inside" that function are created in a piece of "stack" storage that is allocated when the function is called. When you return, that storage is released, to be reused by other functions. The other thing to understand is that arrays, in C, are second-class citizens, and so your `return s` will just return a *pointer* to the array s. The actual storage for s remains allocated in the "stack frame" ... until you return, at which point it goes "poof". – Hot Licks May 21 '13 at 21:57

1 Answers1

4

s is a local variable that only exists within the function.

Once the function exits, s no longer exists, and its memory will be re-allocated to other parts of your program.

Therefore, your function is returning a pointer to a random meaningless block of memory.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 1
    "s is a local variable" - more precisely, `s` is a block-scope object with automatic storage duration, so using it outside of its enclosing block (the function body) invokes undefined behavior. –  May 21 '13 at 21:53
  • @imre: That's a memory leak. – SLaks May 21 '13 at 21:56