1

I've defined two classes CA and CB. I would like to prevent memory leak and I don't know how to properly destroy the class CB (assuming that the memory leak is coming from it). mpz_t is a GMP datatype. Here's my code

class CA {
public:
void SetFoo (unsigned long int);
CA  ();
CA  (unsigned long int);
~CA ();
private:
mpz_t foo;
};

where

CA::CA () {
mpz_init (foo);
}

CA::CA (unsigned long int in) {
mpz_init   (foo);
mpz_set_ui (foo, in);
}

CA::~CA () {
mpz_clear (foo);
}

void CA::SetFoo (unsigned long int in) {
mpz_set_ui (foo, in);
}

and

class CB {
public:
CB  ();
~CB ();
private:
list <pair<uint16_t, CA*>> mylist;
};

where

CB::CB () {
pair<uint16_t, CA*> mypair;
CA* C = new CA [2];
C [0].SetFoo (100);
C [1].SetFoo (200);
mypair.first  = 0;
mypair.second = &C[0];
mylist.push_front (mypair);
mypair.first  = 1;
mypair.second = &C[1];
mylist.push_front (mypair);
}

CB::~CB () {
???
}
dfine
  • 11
  • 1
  • 1
    Not the answer, you don't forget to fix the [rule of three](https://en.cppreference.com/w/cpp/language/rule_of_three) violations. – HolyBlackCat Aug 26 '18 at 11:40
  • Since you new an array you also have to delete the array. You’ll have to keep a reference to it. Or you could just create two separate objects and delete them. – Sami Kuhmonen Aug 26 '18 at 11:40
  • 2
    You never `delete[]` what you `new[]`. Either do that or simply use a smart pointer or stop heap allocating objects when you don't need to. Manual `new`/`delete` is a bad idea 99% of the time. – Jesper Juhl Aug 26 '18 at 11:41
  • Why exactly do you need `C` to point to an array of 2? – Killzone Kid Aug 26 '18 at 11:46
  • it may help https://stackoverflow.com/questions/6261201/how-to-find-memory-leak-in-a-c-code-project – user3592331 Aug 26 '18 at 11:51
  • @Jesper Juhl. Thank you for suggesting smart pointers (I'll google it). Regarding your first comment, I don't know how to call the delete operator over the second element of mypair. – dfine Aug 26 '18 at 11:55
  • 1
    Besides smart pointers, you also need to learn about [the rule of Three](https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three) and implement (at the very least) a copy constructor and an assignment operator; otherwise, in addition to leaks, you will at some point end up dealing with crashes that do not have an obvious cause. – Sam Varshavchik Aug 26 '18 at 12:30

1 Answers1

3

You can use std::unique_ptr instead of a regular pointer. This will automatically deallocate the memory on the destruction of each element.

typedef std::unique_ptr<Ca[]> CA_array;
list <pair <uint16_t, CA_array> > mylist;

Alternatively, you could iterate through the elements and deallocate memory using delete [].

CB::~CB () {
    for (auto &item : mylist) 
        delete [] item.second;
}
Kostas
  • 4,061
  • 1
  • 14
  • 32