Problem with deallocating vector of pointers

Hi guys,
I don't know what's wrong with the following code! I am deleting all pointers, but when I use the "top" command to watch the memory, I can see that still lots of memory is allocated to the program. Am I missing something here to free the memory?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int*> container;
    vector<int*>::iterator itr;
    unsigned long long i;

    for(i = 0; i < 10000000; i++)
    {
        int* temp = new int();
        *temp = 1;
        container.push_back(temp);
    }

    for(itr = container.begin(); itr != container.end(); itr++)
    {
        delete *itr;
        *itr = NULL;
    }

    container.clear();
    cout<<"\nafter clear\n";

    while(1)
    {
        sleep(1000000);
    }

    return 0;
}
Last edited on
Please tell me that it's just a test, and you don't use the dynamic allocation in that way.
check the capacity of your vector
1
2
container.clear();
cout << container.capacity();
I think it is implementation dependent, clear may not deallocate the pointers
Hi,
the value of container.capacity() after clearing the container is: 16777216

of course this is just a test, but could you please tell me if there is anything wrong with the way I am allocating memory that I should avoid?

and just FYI: the version of OS and g++:
Linux version 2.6.18-5-686 (Debian 2.6.18.dfsg.1-13)
(gcc version 4.1.2 20061115 (prerelease) (Debian 4.1.1-21))
http://www.cplusplus.com/forum/beginner/33449/
Using dynamic allocation makes sense when you use polymorphism or want to create an array with unknown size at compilation time(but exists std::vector)
Yours is a waste of resource
Hi!

On Windows the memory usage is deallocated after delete section. However you should check the size and capacity members of the vector. They are different.

http://www.cplusplus.com/reference/stl/vector/size/

http://www.cplusplus.com/reference/stl/vector/capacity/

I think the answer is that after growing size of vector, it holds the memory usage. In other words the memory usage is caused by empty allocated memory space of the vector.
Topic archived. No new replies allowed.