开发者

vector hold memory even swap with an another empty vector

I make a tiny experiment, code is as following :

    vector<char> *p = new vector<char>[1024];
    for (size_t i = 0; i < 1024; i++) 
    {
  开发者_运维百科      (*p++).resize(1024 * 1024);//alloc 1 G memory 
    }

    sleep(5);
    cout << "start to clear" << endl;
    for (size_t i = 0; i < 1024; i++)
    {
        vector<char> tmp;
        tmp.swap(*p++);
    }
    delete [] p;

    cout << "clear over!" << endl;
    sleep (5);

//here, the memory is still 1G, why ? thank you very much.


In most implementations, the memory isn't returned to the OS immediately, but rather put into a "free list", as acquiring memory from the OS is often way more expensive than walking such a free list. That's most likely why you still see the 1gig of memory, wherever you check that.

Also, in your code, I don't see where you reset p after reserving all the vectors, you basically swap the empty vector with uninitialized memory that doesn't belong to you.


You didn't reset p to its initial value between the two loops. The second loop doesn't clear the initial p, it messes with random memory after the memory allocated for the initial p.

I suggest you use (*(p + i)) or (p + i)-> or p[i] instead of (*p++). Or even better, use vector<vector<char> >. And instead of swapping with a temporary vector. use the clear() member function.

Edit: Here's two good implementations

vector<char>* p = new vector<char>[1024];
for( size_t i = 0; i < 1024; i++ ){
    p[i].resize(1024 * 1024);
}
sleep(5);
cout << "start to clear" << endl;
for( size_t i = 0; i < 1024; i++ ){
    p[i].clear();
}
delete [] p;
cout << "clear over!" << endl;
sleep(5);

vector<vector<char> > p(1024);
for( size_t i = 0; i < 1024; i++ ){
    p[i].resize(1024 * 1024);
}
sleep(5);
cout << "start to clear" << endl;
for( size_t i = 0; i < 1024; i++ ){
    p[i].clear();
}
cout << "clear over!" << endl;
sleep(5);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜