Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is checking the value of a dangling pointer safe or Undefined Behavior? [duplicate]

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.

like image 615
Itachi Uchiwa Avatar asked Sep 30 '21 19:09

Itachi Uchiwa


1 Answers

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.

like image 158
eerorika Avatar answered Oct 10 '22 14:10

eerorika