0

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.

Ry-
  • 218,210
  • 55
  • 464
  • 476
lasvig
  • 181
  • 4
  • 13
  • 3
    Why are you using vectors for the `list` member *and not for the `child` member*? – R. Martinho Fernandes Jun 28 '13 at 14:28
  • 5
    That's the usual stuff - freed memory isn't returned immediately to the OS, but is kept by the allocator, so it's normal you don't see an immediate decrease in memory usage. – Matteo Italia Jun 28 '13 at 14:29
  • 1
    the setup dont matter here as it is just a test. if i understand correctly than Matteo, the memory should be freed when needed? so if i try to fill up the memory again after deleting it would return as needed? – lasvig Jun 28 '13 at 14:35

1 Answers1

2

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"

Community
  • 1
  • 1
dbrank0
  • 9,026
  • 2
  • 37
  • 55