1

When we run this piece of code, it works normally and prints string constant on the screen:

char *someFun(){
    char *temp = "string constant";
    return temp;
}
int main(){
    puts(someFun());
}

But when we run the following similar code, it won't work and print some garbage on screen:

char *someFun1(){
    char temp[ ] = "string";
    return temp;
}
int main(){
    puts(someFun1());
}

What is the reason behind it? Essentially, both functions do similar things (i.e. return a "string"), but still they behave differently. Why is that?

Palec
  • 12,743
  • 8
  • 69
  • 138
buch11
  • 872
  • 3
  • 13
  • 29

2 Answers2

5
char *temp = "string constant";

string constant literal resides on read only segment. It gets deallocated at program termination. So, you can have a reference pointing to it.

char temp[ ] = "string";

string is copied to temp which resides on stack. As the function returns, unwinding of stack begins which de-allocates the variables in the function scope. But you are returning a reference to it which no longer exists on stack and hence you are getting garbage. But sometimes you may still get the correct result but you should not rely on it.

Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
Mahesh
  • 34,573
  • 20
  • 89
  • 115
  • 1
    Arguments, control information like return address and frame pointer, and local variables in `puts()` may be using the space previously used by the local variable (array) in `someFun1()`. – Jonathan Leffler Sep 17 '11 at 06:28
  • 2
    Incidentally, to avoid problems when handling string literals you should store pointers to them inside `const char *` variables, so the compiler will block you if you try to modify them. – Matteo Italia Sep 17 '11 at 13:32
3

In the first case, the pointer temp will point to a global constant storing "string constant". Therefore, when you return the pointer, it's valid.

In the second case, '"string"' is just a char array on the stack - which dies after you return from the function.

Mysticial
  • 464,885
  • 45
  • 335
  • 332
  • why in first case it is stored on the global heap,and in the second case in a local stack? – buch11 Sep 17 '11 at 06:13
  • 2
    String literals, by default, are stored globally. (not on the heap, but in the program memory) However, when you declare char[], you're allowed to put a string there as a short-form for `{'s','t','r','i','n','g'}`. – Mysticial Sep 17 '11 at 06:15
  • ... including the null terminator. – Jeff Mercado Sep 17 '11 at 06:25