I tried comiling on linux and windows, in both cases it worked. |
As LB pointed out, the behavior is undefined. That means the program might crash, or it might not compile, or it might display 7, or it might display a random value.
You might run it a million times and it might display 7, then on the million and one'th time, it displays some other number. In fact, on many systems this is exactly what will happen.
Why does it display 7? Because
a
in foo and
a
in var happen to be allocated at the same address on the stack and the system happened to put nothing there between the calls.
Why didn't you get segmentation violation? There's a difference between the what memory the C++ program is using at any given time and what memory the operating system has allocated to it. A SEGV will happen if the program tries to allocate memory that the OS has not allocated to it. In this case, the OS allocated some memory, the stack can grow into that memory, but the program isn't currently using it.
Why might the result be different after a million runs? It's the fact that
p
probably points to the far side of stack pointer. If the computer gets an interrupt between the call to boo() and the time that you print *p, then it might, depending on the computer, use the program's stack when servicing the interrupt. That means it might write who-knows-what at that location.
This may all be interesting, but you can't rely on any of it. To reiterate, the behavior is
undefined. The program can do whatever it wants. There is no such thing as "incorrect" behavior in this case.