lasvig
lasvig

Reputation: 191

How can I free memory of a object containing a std::vector

In a program I am currently working on, I have objects containing std::vectors. The problem arise when I try to delete these objects, no memory is freed from the object.

I made a minimal program to test this and can't make it work correctly in this program either.

Here is the program I used to test.

#include<iostream>
#include<vector>

struct node{

    std::vector<int> list;

    bool isParent;
    struct node* child;

    ~node(){
        delete[] child;
    }

    node(){
        isParent = false;
        list.push_back(5); // comenting this line would make it work correctly
    }

    void divide_r(){
        if (isParent){
            for(int i = 0; i < 8; i++){
                (child+i)->divide_r();
            }
        }else{
            node *c;
            c = new node[8];
            child = &c[0];
            isParent = true;
        }
    }
};

int main(){


    node *root = new node;

    for(int i = 0; i < 8; i++){
        root->divide_r();
    }

    delete root;

    sleep(10);

    return 0;
}

So, if I push anything into the vector, I can't free up any memory.

I am using g++ on ubuntu if that matters. Am I doing anything wrong or should this work?

I have also tried to use different methods to free memory from "list" in the destructor , but as "list" will fall out of scope it should be freed anyway, I guess.

The program will use about 1.4GB of RAM, but nothing gets freed before after sleep and the program exits.

Upvotes: 0

Views: 241

Answers (1)

dbrank0
dbrank0

Reputation: 9466

Try to allocate your objects, then delete them. When you allocate new objects, you will notice, that OS does not show increased memory usage.

You could also run your sample through valgrind, and you should notice, that it does not complain of memory leaks.

The reason is obvious. C library wants to avoid additional overhead of calling OS to allocate and return each small chunk of memory.

Related threads: Linux Allocator Does Not Release Small Chunks of Memory, Does calling free or delete ever release memory back to the "system"

Upvotes: 2

Related Questions