RealityVelJackson
Programmer
I was under the impression that one shouldn't return pointers to variables that are created inside of a function, unless the variable was static or allocated on the heap. Why does the following code work fine ? In foo1() since
str points to a string-literal, I guess the string-literal is allocated in a memory location outside of the stack frame, so it won't be deallocated when the function returns.
If this is true then I have no problem here.
I'm confused by the fact that the value in int x is not wiped-out when foo2() returns. My understanding is that int x is created on the stack-frame and deallocated by the time control is passed back to main(). How could a pointer to a deallocated auto variable still retrieve the value ?
str points to a string-literal, I guess the string-literal is allocated in a memory location outside of the stack frame, so it won't be deallocated when the function returns.
If this is true then I have no problem here.
I'm confused by the fact that the value in int x is not wiped-out when foo2() returns. My understanding is that int x is created on the stack-frame and deallocated by the time control is passed back to main(). How could a pointer to a deallocated auto variable still retrieve the value ?
Code:
#include <stdio.h>
char* foo1();
int* foo2();
int main(){
char* s;
int* d;
s = foo1();
printf("%s\n", s);
d = foo2();
printf("%d\n", *d);
return 0;
}
char* foo1(){
char* str = "hello";
return str;
}
int* foo2(){
int x = 8;
return &x;
}