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?
string constantliteral resides on read only segment. It gets deallocated at program termination. So, you can have a reference pointing to it.stringis copied totempwhich 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.