Deallocating vector of pointers, but memory still

2019-05-29 01:37发布

问题:

I have no idea 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?

#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;
}

回答1:

There is no leak in this code (Assuming there are no exceptions being thrown after allcoation and before deallocation). The reason why that you are not seeing memory coming down is that the CRT may not release the memory you delete immediately back to the process. It might keep it for future use. However, it is guaranteed that the memory will be released once the process terminates.



回答2:

As Naveen said, there is no leak in the code. But, the way you are writing loop is not recommended. You could have easily used for_each() to delete the memory. refer to this question in SO