-2
void* func1(int a)
{
    void *b = &a;
    return b;
}

int main(int argc, char** argv) {
    int d = 9;
    
    void *c = func1(d);
    printf("%d\n", *((int*)c));
    
    return 0;
}

I am confused about why it works.
From my understanding, memory of "a" will release after func1.

Why the void* c can still access "a" after finish the function?

  • 6
    This program exhibits undefined behavior. "Seems to work" is one possible manifestation of undefined behavior. Practically speaking, it just so happens that the spot on the stack where `a` used to sit has not been overwritten yet with some other data. In fact, if you just call `printf` a second time, [it'll print garbage](https://godbolt.org/z/4M931P), because the first call used the stack and overwrote that spot. – Igor Tandetnik Aug 28 '20 at 03:43
  • 2
    @IgorTandetnik `it'll print garbage` Minor, pedantic, correction: It **may** print garbage. After all, there are no guarantees. It might not print anything, and it may or might not do anything else. Arguably, the printed 9 was already garbage. It just happens to be garbage that OP mistakenly was expecting to not see. – eerorika Aug 28 '20 at 04:01

1 Answers1

4

I am confused about why it works.

The behaviour of the program is undefined. The program doesn't "work" - In my opinion. Although "workingness" may be subjective.

From my understanding, memory of "a" will release after func1.

Correct.

Why the void* c can still access "a" after finish the function?

Behaviour of the program is undefined. Appearance of having particular behaviour is within the limits of undefined behaviour. Anything is within limits of undefined behaviour because the language imposes no limits on behaviour of the program.

eerorika
  • 232,697
  • 12
  • 197
  • 326