Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for non-deallocated pointer

Assume a pointer object is being allocated on one point and it is being returned to different nested functions. At one point, I want to de-allocate this pointer after checking whether it is valid or already de-allocated by someone.

Is there any guarantee that any of these will work?

if(ptr != NULL)
   delete ptr;

OR

if(ptr)
   delete ptr;

This code does not work. It always gives Segmentation Fault

#include <iostream>
class A
{
    public:
    int x;
     A(int a){ x=a;}
     ~A()
     { 
          if(this || this != NULL) 
              delete this;
     }
};
int main()
{ 
    A *a = new A(3);
    delete a;
    a=NULL;
}

EDIT

Whenever we talk about pointers, people start asking, why not use Smart Pointers. Just because smart pointers are there, everyone cannot use it.

We may be working on systems which use old style pointers. We cannot convert all of them to smart pointers, one fine day.

like image 748
cppcoder Avatar asked Feb 10 '26 13:02

cppcoder


1 Answers

if(ptr != NULL) delete ptr;

OR

if(ptr) delete ptr;

The two are actually equivalent, and also the same as delete ptr;, because calling delete on a NULL pointer is guaranteed to work (as in, it does nothing).

And they are not guaranteed to work if ptr is a dangling pointer.

Meaning:

int* x = new int;
int* ptr = x;
//ptr and x point to the same location
delete x;
//x is deleted, but ptr still points to the same location
x = NULL;
//even if x is set to NULL, ptr is not changed
if (ptr)  //this is true
   delete ptr;   //this invokes undefined behavior

In your specific code, you get the exception because you call delete this in the destructor, which in turn calls the destructor again. Since this is never NULL, you'll get a STACK OVERFLOW because the destructor will go uncontrollably recursive.

like image 185
Luchian Grigore Avatar answered Feb 13 '26 04:02

Luchian Grigore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!