DEV Community

Discussion on: When does a pointer become dangling in C/C++? | Why isn't this example dangling?

Collapse
 
baenencalin profile image
Calin Baenen

So, the same as I replied to someone on Twitter who had a pretty similar answer; and as you said by saying I'm "getting lucky": The compiler that SoloLearn was just being merciful in its decision not to provide a segfault?

Collapse
 
deciduously profile image
Ben Lovy • Edited

A segfault always comes from the OS, not the compiler, when you hit memory that's "not yours". In this case, the compiler did what you asked, it showed you the memory at that location. I believe the other comment is correct about why this is reproducible, both i and p live in the stack frame allocated for main(), which still exists when the printing happens, so nothing has had a chance to interfere even though you're pointing to a variable that isn't in scope. The memory is still "yours", as in, belongs to the program, even though semantically within your program it's out of scope, so the OS doesn't complain. However, it's not guaranteed to be reproducible, and different compilers are free to handle this in totally different ways.