1

May be this is very dumb question. But I don't know answer to this.

If object to which pointer is referring is deleted by someone( we don't know who is deleting it ), but I still have raw pointer to it. The how to validate if its a valid or not. I though null check would help, but it does not.

Here is an example:

int main()
{
   class A
   {
   public:
      A() = default;
      ~A() = default;
   private:
      int a;
      long b;
   };

   A* a = new A();
   delete a; // deleted here
   A* b = reinterpret_cast< A* >( a ); // still trying to use it 
   if( b == nullptr )
      std::cout << "B is Null"; // b should have come as null, but it does not and I do not see this line in output.

   // same here
   A* c = ( A* ) a;
   if( c == nullptr )
      std::cout << "C is null";
   getchar();
    return 0;
}

enter image description here

If you see in above picture, a is not null, and has some garbage values.

I know this is very naïve code, but this show problem that I have with actual code.

Thanks, Kailas

granmirupa
  • 2,780
  • 16
  • 27
Kailas
  • 807
  • 1
  • 6
  • 20

2 Answers2

3

No, you can't know whether a pointer points to valid memory.

From here:

Because it would be expensive to maintain meta data about what constitutes a valid pointer and what doesn't, and in C++ you don't pay for what you don't want.

Moreover, you don't really need to check if a pointer is valid because you, as programmer, know where the pointers come from.

Community
  • 1
  • 1
granmirupa
  • 2,780
  • 16
  • 27
-5

You can check using if(!a) or if(a) for validating.

  • What about on systems where 0 is a valid address (vector table pointers and such)? This is a bit too broad of a statement as is commented elsewhere. – Michael Dorgan May 09 '17 at 19:50