0

I have stumbled upon a program behaviour that I couldn't understand:

int* g(int i)
{
    i = 1;
    return &i;
}

void main() {
    int* j = g(5);
    printf("%d", *j);
}

I used to think that the parameter, i , that was recieved in function g would be deallocated from the stack after g is done. For some reason, the memory isn't deallocated and j holds the value of 5 when printf is called. What is the reason for this?

Tl2
  • 61
  • 6
  • 1
    When you see something "works" when it shouldn't, chances that you are observing a result of *undefined behavior*. Which is exactly the case here. – Eugene Sh. Jun 23 '20 at 18:11
  • 1
    It may happen to work sometimes, but it's undefined behavior and you can't count on it. The argument `i` in `g` is essentially a local variable of the function, and it goes out of scope when the function returns. – Tom Karzes Jun 23 '20 at 18:12
  • 3
    When memory is deallocated, it doesn't mean that the old contents are removed. It just means that it's available for reuse in the future. In your test the memory hasn't been reused yet, so you see the old contents. – Barmar Jun 23 '20 at 18:17

0 Answers0