0

Let's say we have the following code. st is a global stack and is initialized properly. We call foo()

struct stack *st;

int foo() {
    int x = 1;
    stack_push(st, &x);
}

Now, the stack contains a pointer to x. After foo goes out of scope, what happens to the address &x? Is it deallocated? Can we trust that when we pop() the stack later on and dereferenced it that the value will be 1?

edit: Here's what I'm currently thinking. Since x is allocated on the stack, once it goes out of scope, the memory occupied in address &x can be used by anyone therefore the dereferenced value returned by pop() later on can possibly be not 1.

  • 3
    It is undefined behavior. It could spawn a chorus line of New York sewer rats in your basement for all you know. – WhozCraig Mar 08 '13 at 05:48
  • Please put some minimal effort into the search engine of this site. This question is asked at least 3 times per day. – Lundin Mar 08 '13 at 07:43

2 Answers2

2

The behavior at the point foo returns is undefined. Often the value will be maintained until the next method call creates a large enough stack to over write it. But depending on this is wrong and shouldn't be done.

If you need x to live longer than foo then you need to allocate memory for it on the heap

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • thanks. That's what I was thinking as well, I just had to make sure. I have to wait 10 more minutes to accept this. –  Mar 08 '13 at 05:50
0

The global stack hold the pointer pointing to x all the time until global stack is destroyed. But after foo goes out of scope, the stack space occupied by x before could be reused. May be caused by foo() re-entered, or by other function invocation, or any other stack space allocation.

Hardy Feng
  • 459
  • 4
  • 13