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;
}
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
deleteimmediately 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.