advice on how to free memory leak

Hi everyone!

I have to deal with a memory leak in a code that is not mine, and I want to ask for advice on what is an elegant way to free the memory leak. The code looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

#include <iostream>
#include <vector>
using namespace std;

class A
{
public:

    int a;

    A(int a_) : a(a_)
    {}
};

class B
{
public:

    B(A * a) : a_(a)
    {
    }
private:
    A *a_;

};

class Example
{
public:

    void createElements(int count)
    {
        vectorB.clear();
        for (int i = 0; i < count; i++)
        {
            A * a = new A(i);
            B b(a);
            vectorB.push_back(b);
        }
    }

private:
    std::vector <B> vectorB;
};


int main()
{
    Example example;
    example.createElements(3);
}






The memory leak comes from the line 37

I thought that maybe I could maintain a vector<A*> and add the objects to this vector. Then, when deleting Example (or when calling createElements again) I would iterate through that vector, free its elements and clear the vector.

What do you think about this approach?

Thanks a lot!

Last edited on
Use value semantics, perhaps?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class A
{
    public:
        int a;
        A( int a_ ) : a(a_) {}
};

class B
{
    public:
        B( int v ) : a_(v) {}

    private:
        A a_; // an object of type A
};

class Example
{
    public:

        void createElements( int count )
        {
            vectorB.clear();

            for( int i = 0; i < count; ++i )
                vectorB.emplace_back(i) ; // C++98: vectorB.push_back( B(i) ) ;
        }

    private:
        std::vector <B> vectorB;
};
Topic archived. No new replies allowed.