Home > Mobile >  Couldn't free allocated memory using delete
Couldn't free allocated memory using delete

Time:12-31

I'm allocating memory in a member function like below:

void Wrapper::PutData() {

mpeople.append(new people("ALPHA","BEETA","GAMMA", this));
mpeople.append(new people("ALPHA","BEETA","GAMMA", this));
mpeople.append(new people("ALPHA","BEETA","GAMMA", this));

}

where the mpeople object is declared as

QList<QObject*> mpeople;

Everything works fine until i try to remove items using the below member-function

void Wrapper::RemoveClient(int index){
    if(index >= 0){
        delete[] mpeople[index];
        mpeople.removeAt(index);
    }
    resetModel();
}

CodePudding user response:

You're attempting to do scalar delete on an object that wasn't allocated with scalar new. That is delete, not delete [].

Just do this:

void Wrapper::RemoveClient(int index){
    if(index >= 0){
        delete mpeople[index];
        mpeople.removeAt(index);
    }
    resetModel();
}

A more modern way, is to use shared_ptr or unique_ptr or the equivalent qt smart pointer class.

Declare like this:

QList<std::shared_ptr<QObject>> mpeople;

Insert like this:

mpeople.append(std::make_shared<people>("ALPHA","BEETA","GAMMA", this));

Remove like this:

mpeople.removeAt(index); // pointer will get deleted for you when the last reference goes away
  • Related