A function call&return issue

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;
}
The memory that was used by x is still there. It has probably not been used by anything else yet so it still stores the value 9.
Last edited on
So the function call stack section will not be "deallocated" by the compiler, instead it will be overwritten. Thanks for the reply.
Choice of compiler and compiler options (debug vs. optimized) can affect the undefined behaviour too.
Topic archived. No new replies allowed.