user1623990
user1623990

Reputation: 35

Memory leak in vector of pointers, how to prevent?

I'm getting a bit of a memory leak in my program and this is about the only thing I think it could be.

if (inputType == 'S')
{
    SavingAccount* savingAccount = new SavingAccount();
    inFile >> *savingAccount;

    accounts.push_back(savingAccount);
}

While the vector of pointers is deleted at the end of the program, I am having 3 error leaks which seem to correspond with the 3 types of accounts I have. That being said, if I delete the pointer after putting it into the vector, it deletes the entry in the vector as well (which I expected)

Does anyone know how to resolve this?

EDIT:

void Transaction::cleanUp()
{
    for (int i = 0; i < accounts.size(); i++)
    {
        delete accounts[i];
    }

    accounts.clear();
}

clean up code added.

EDIT: RESOLVED

My issue didn't have as much to do with the vector as it did the destructors of the classes. As I had not defined a virtual destructor only the base class was being erased, leaving behind fragments of the derived classes. There is no no memory leak after adding this.

Upvotes: 2

Views: 3798

Answers (4)

Tony The Lion
Tony The Lion

Reputation: 63200

Why do you need pointers in your vector? I haven't seen much of your code, but AFAIK this below could work just as well, if your SavingAccount class is copy constructible:

if (inputType == 'S')
    {
        SavingAccount savingAccount;
        inFile >> savingAccount;

        accounts.push_back(savingAccount); //puts a copy in the vector, so your class needs a copy ctor + Rule of Three applied.
    }

EDIT

Seeing OP says he has a polymorphic class structure, then OP should use a std::unique_ptr and store that in the std::vector or consider using boost::ptr_vector which is designed for storing pointers.

Upvotes: 8

juanchopanza
juanchopanza

Reputation: 227418

Either use an std::vector of std::unique_ptr<SavingAccount> or loop over the vector, deleting all elements before the vector goes out of scope or gets deleted.

Upvotes: 3

Kiril Kirov
Kiril Kirov

Reputation: 38173

Delete the SavingAccount*, stored in you vector, before the destroying of the vector.

Or use smart pointers, if you can.

Upvotes: 2

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143099

You can either delete before destroying the vector or store smart pointers in the vector.

Upvotes: 2

Related Questions