0

I have a class Aclass which contains a pointer to struct GraphStructure *Graph_.

The Aclass constructor initializes this pointer by dynamically allocating a GraphStructure instance.

The GraphStructure instance also dynamically allocates arrays and calls delete on these in its destructor.

The order in which the destructors are called are (1) the class destructor and (2) the struct destructor.

If I call delete on Graph_ in the Aclass destructor and then the destructor for the struct is called, is there a double free happening here as my program stops responding.

If I don't call delete Graph_; then it runs ok but am I not introducing a memory leak here? What is the correct way to handle this?

I've tried to debug the program.

struct GraphStructure
{
    idx_t* xadj;                     
    idx_t* adjncy;                    

    GraphStructure() {

        xadj = new idx_t[5]; 
        adjncy = new idx_t[5];

    }   

    ~GraphStructure() {
        delete[] xadj;
        delete[] adjncy;
    }
};


class Aclass 
{
    GraphStructure *Graph_;
 }



Aclass::Aclass():Graph_(new GraphStructure()) {}

Aclass::~Aclass()
{
//delete Graph_;
}
black sheep
  • 369
  • 4
  • 13
  • 4
    Don't use naked `new`, use smart pointers instead. Or `std::vector` for arrays. – Max Langhof Apr 17 '19 at 10:53
  • 4
    Use smart pointers and containers instead of managing memory allocation yourself. – πάντα ῥεῖ Apr 17 '19 at 10:53
  • 1
    Also, the premise of the question is wrong. If you do `delete Graph_` in `~Aclass` there is no double free in itself. The problem likely comes from incorrect copy constructors. Read up on the rule of five and the rule of zero. Further reading: https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three – Max Langhof Apr 17 '19 at 10:55
  • explicit use of `new` `delete` is not recommended nowadays. See this: https://youtu.be/JfmTagWcqoE – Marek R Apr 17 '19 at 11:02

0 Answers0