We can only de-reference a valid pointer and we can only check the address that a dangling built-in pointer points to. We cannot access its value (the value in the address of object it is pointing to).
int* ptr = nullptr;
if(ptr) // != 0x00000000
std::cout << *ptr << '\n';
ptr = new int(1000);
if(ptr) // != 0x00000000
std::cout << *ptr << '\n';
delete ptr; // still pointing at the address of that dynamic object but that object has been destroyed.
if(ptr) // succeeds or undefined behavior?
std::cout << *ptr << '\n'; // of course UB here
So it is clear for me but what matter me only is whether checking a pointer value is safe or yields UB? if(ptr)
. Because let's assume that I didn't access the value in that address like in std::cout << *ptr
.
Is checking the value of a dangling pointer safe or Undefined Behavior?
It's not UB (since C++14), but "safe" depends on what you expect. There is no guarantee about the result of such check. It could be true or false. Assuming that a pointer is valid based on if(ptr)
is not safe in general.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With