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
.
nullptr
unfortunately does not check whether the pointed-to object has been destroyed or not. (Obviously, if the pointer isnullptr
there is no pointed-to object, but the flip side does not hold.) – Poddy