-3

I have a class with the .h file as:

class dbsk2d_ishock_node : public dbsk2d_ishock_elm{
protected:
    dbsk2d_ishock_edge* _cShock;
    //Some other variables
public:
    dbsk2d_ishock_node (int newid, double stime, vgl_point_2d<double> Or); //Constructor
    virtual ~dbsk2d_ishock_node (); //Destructor
    //Some other functions
}

The .cxx file looks like:

//Constructor
dbsk2d_ishock_node::dbsk2d_ishock_node (int newid, double stime, vgl_point_2d<double> Or) : dbsk2d_ishock_elm (newid, stime)
{
    _cShock = NULL;
    //Some other variables
}

//Destructor
dbsk2d_ishock_node::~dbsk2d_ishock_node ()
{
    _cShock = NULL;
    //Some other variables
}

Now the constructor for this class sets _cShock = NULL; and the virtual destructor also sets _cShock = NULL;.

So when the destructor is called, it will just set the pointer to NULL but the actual memory being poined to won't be destroyed, right, causing a memory leak?

This class is called many times and after a certain point the program crashes due to excessive memory usage. How do I fix this?

JeJo
  • 30,635
  • 6
  • 49
  • 88

2 Answers2

3

So when the destructor is called, it will just set the pointer to NULL but the actual memory being poined to won't be destroyed, right, causing a memory leak?

YES. It will.

How do I fix this?

you can delete the pointer like

~className()
{
   delete dbsk2d_ishock_edge;
}

or Best practice is using Smart Pointers as member variables, by including <memory>. You can also refer this, as it look like you are not aware of them. For instance:

protected:
    std::shared_ptr<dbsk2d_ishock_edge>  _cShock;
JeJo
  • 30,635
  • 6
  • 49
  • 88
0

As you set the pointer to NULL in the constructor you could safely free the memory doing this

~className() { 
    if (dbsk2d_ishock_edge){
        delete dbsk2d_ishock_edge;
        dbsk2d_ishock_edge = NULL;
    }
}
Alberto Valero
  • 410
  • 4
  • 14
  • 2
    Why are you checking for `!= NULL`? And why are you setting the pointer to `NULL` afterwards? – melpomene May 25 '18 at 18:46
  • 1
    I think you mean "destructor". – DaveG May 25 '18 at 18:46
  • 3
    you don't need check for NULL (or, rather, nullptr), NULL is delete's friend. – Swift - Friday Pie May 25 '18 at 18:46
  • @melpomene the pointer is set to NULL in the constructor. It could happen that the new is never being called, if you call delete on an not intialized pointer you could get a segfault. I set to NULL afterwards because if I have copied the ptr address to some other variable in this way I can know it does not exist anymore. Just extra safety – Alberto Valero May 25 '18 at 18:49
  • 1
    @AlbertoValero The pointer is set to `NULL` in the constructor. It is never uninitialized. On the other hand, if the pointer actually is uninitialized, then `if (dbsk2d_ishock_edge != NULL)` has undefined behavior. – melpomene May 25 '18 at 18:50
  • @Swift-FridayPie all my life checking... Thanks. Not any more! – Alberto Valero May 25 '18 at 18:51