@zapshe
^For some reason though, it seems to work just Fine on Visual Studio 🤷♀️ |
It may seem to work on a wide variety of compilers and platforms.
A lot may depend on how the compiler optimizes the code, if optimization is on, and some may be the behavior of the compiler interpreting this code.
There isn't really a requirement that int x be placed on a new level of the stack. It could, certainly, and in other contexts where code is more complex before and/or after this clause, but there may not actually be a stack manipulation here, meaning x still actually exists as if it had been declared before the "if" clause.
Of course there's no guarantee of this, as there is an implication of a stack stored local variable.
Even if the "if" clause were inside a function called by main, and if the pointer p had been assigned to this stack resource, where we also know there is an implication that a local stack was created for the function call and released after it returned, this code would likely still seem to work because little has happened to that point which corrupted the content left behind from the function call. There will be a call to the functions for "std::cout", but at the moment the content of p is dereferenced that has not happened, and it is likely that this would still seem to work.
Then, if one other function were called between the assignment of p (and the release of x) before the "cout<<" was called, THAT could corrupt the stack and THEN we'd have proof this failed.
Valgrind or similar memory debugging software would probably notice this, as would many code analysis tools and some compiler's warnings might mention it.