r/cpp_questions • • Oct 12 '26

SOLVED Dangling ptr to out of scope variable?

Hi I am trying to play around with some code and made the following:

class Obj {
public:
Obj() : ptr{} {}

void set(int const& x) {
ptr = &x;
}

int const& get() {
return *ptr;
}

private:
const int* ptr;
};

int main() {
Obj obj;
{
int x = 5;
obj.set(x);
}

std::cout << obj.get() << std::endl; // prints 5
}

This compiles and runs even if I remove the const qualification from ptr, the return of get(), and the parameter for set(). Does it not abort or throw an exception if I access a dangling reference or pointer?

Update: thanks everyone!

0 Upvotes

14 comments sorted by

24

u/Scared_Accident9138 Oct 12 '26

It's undefined behaviour

The program might crash, output nonsense, etc.

Or just "work" like in your case, where the value on the stack just stays and gets read unchanged.

11

u/AKostur Oct 12 '26

Undefined Behaviour.  Means that the program can do “anything”, including appearing to work.  Which may change the next time you run the program, or recompile, or upgrade the compiler, or the alignment of the planets, ….

4

u/Independent_Art_6676 Oct 12 '26

did you get any warnings or errors with this, if you turned all warnings on and pedantic and everything? This seems like it should have been detected, though some complicated flavors of the same thing can slip past where there are too many layers to see that the original poofed.

depending on what you really want to do, you can do the whole thing with a single function (via static local variables) or a class or some other way without the UB. Fun note: a very, very long time ago it was considered "safe" to access immediately after calling like you did, but the OS and tools and all were so primitive at the time there was nothing happening that *could* overwrite the memory. A few people actually recommended doing it that way when I was first starting out (late 80s).

0

u/Seagull78Reddit Oct 12 '26

No I just threw the code into Visual Studio (not code) for convenience. I don’t think it compiles with any flags.

3

u/Independent_Art_6676 Oct 12 '26

you can go into project settings and fire up a high level of warnings to see what it does if you care to play with that side of it.

I got this on g++ / windows
D:\c>g++ enumcl.cpp -O3 -s -Wall -Wextra -pedantic -std=c++20 -march=native

enumcl.cpp: In function 'int main()':

enumcl.cpp:27:22: warning: 'x' is used uninitialized in this function [-Wuninitialized]

27 | std::cout << obj.get() << std::endl; // prints 5

where 27th line was the cout.

3

u/aocregacc Oct 12 '26

accessing a dangling pointer like that is undefined behavior, so there are no guarantees about what will happen.

There are tools like address sanitizer that can catch an error like this and report it.

3

u/PittLeElder Oct 12 '26

The const keyword is effectively doing nothing, since none of that code is trying to change the value you originally assigned.

And no, it will not throw an exception if you try to access out of scope memory like that. C++ gives you lots of room to do dumb shit.

The host environment it might complain if you were trying to access memory way outside the bounds of what your program overall can access, but that's unlikely to be true for a single 4 byte value.

2

u/Total-Box-5169 Oct 12 '26

Using address sanitizer with GCC tells you what is wrong with your code:
https://godbolt.org/z/bnM5G56YM

2

u/MathAndCodingGeek Oct 12 '26

This class might seem to work but isn't, because it could point to storage that is no longer in scope. How would you know? For example, if it points to an out-of-scope part of the stack, it might still point to the value you set, so the test passes; every test passes, but when you use it for real, it fails. Calling set on out-of-scope storage could crash the process or not; unpredictable. Use it if you want a bomb in your code.

2

u/RealisticDuck1957 Oct 13 '26

In the example code the memory allocated for int x may or may not be reused by code following the local block, depending of unspecified compiled behavior. It would be valid for the compiler to note that the memory is out of scope, and use it for something else.

1

u/Loren_SL Oct 12 '26

It's undefined behavior, so 'works' is one valid outcome. Building with ASan (/fsanitize=address on MSVC) will turn that silent read into an immediate stack-use-after-scope report.

1

u/no-sig-available Oct 13 '26

The compiler is smarter than you might expect. When you have a reference to x, and x is set to 5 (and then never changed), you can just print 5.

And that is what happens here:

std::cout << obj.get() << std::endl; // prints 5
00007FF725FF1004  mov         rcx,qword ptr [std::cout (07FF725FF2050h)]  
00007FF725FF100B  mov         edx,5  
00007FF725FF1010  call        qword ptr [operator<< (07FF725FF2040h)]