I'm running the following code and it outputs 9. As I understand, variable x and ptr are allocated in the stack section of getInt() function and when it returns these two variables go out of scope. So in the main function the result of calling getInt() will be a copy of ptr which stores the location of variable x which should be out of scope and its location should be deallocated since the function call has returned. Why does it still print 9? Am I missing something? Really appreciate any help for this.
1 2 3 4 5 6 7 8 9 10 11 12 13
int* getInt()
{
int x = 9;
int *ptr = &x;
return ptr;
}
int main()
{
printf("%d", *getInt());
getchar();
return 0;
}