Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Couldn't free allocated memory using delete

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading