Henke
Henke

Reputation: 125

Memory leakage when trying to remove an object in C++

I have a dynamically allocated array and I am trying to remove a chosen object from it. But I end up with memory leakage. Array:

Competitor* *person;

Which is allocated:

person = new Competitor*[capacity];
for (int i = 0; i < this->capacity; i++) {
    person[i] = nullptr;
}

This is my removal function:

bool Handler::removeCompetitor(string name) {
    bool removed = false;
    if (find(name) != -1) {
        Competitor* *temp = new Competitor*[capacity];
        int j = 0;

        for (int i = 0; i < nrOfCompetitors; i++) {
            if (person[i] != person[find(name)]) {
                temp[j] = person[i];
                j++;
            }
        }
        delete[] person;

        nrOfCompetitors -= 1;
        person = temp;
        removed = true;
    }
    return removed;
}

And this is my find function:

int Handler::find(string name) const {
    int found = -1;
    for (int i = 0; i < nrOfCompetitors; i++) {
        if (person[i]->getName() == name) {
            found = i;
        }
    }
    return found;
}

The class "Competitor" is an abstract base class. Why do I end up with memory leakage?

Upvotes: 0

Views: 35

Answers (1)

user4581301
user4581301

Reputation: 33931

After removing the Competitor* from the array by creating a new array that does not include the Competitor*, you very likely need to delete the Competitor *.

Right before delete[] person; add delete person[find(name)];

If you really want to be sneaky, up at the top found = find(name); and use found instead of re-finding name over and over.

Upvotes: 1

Related Questions