Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Std::deque does not release memory until program exits

Tags:

c++

stl

deque

On linux, std::deque does not release memory until program exits. The complete code is below. Any help will be greatly appreciated!

#include <deque>
#include <vector>
#include <string>
#include <iostream>
#include <boost/shared_ptr.hpp>
#include <queue>
#include <list>
#include <cstdio>
#include <cstdlib>

typedef  boost::shared_ptr<std::vector<int> > VecPtr;
typedef  std::deque< VecPtr  > QueueType;

 char buf[1024];
 char line[1024];

 int main()
 {

  {

    int v=0;
    QueueType  deq;
    for(int i=0; i<30;++i)
    for(int j=0; j<1000;++j)
    for(int k=0;k<1000;++k)
    {
       VecPtr p( new std::vector<int>);
       deq.push_back(p);
    }

    std::cout<<"Done with increasing deq:deq size="<<deq.size()<<std::endl;
    sleep(20);

    std::cout<<"start decreasing deq size"<<std::endl;
    while(deq.size()>0)
    {
      deq.pop_front();
    }
    std::cout<<"done with decreasing deq size,deq size="<<deq.size()<<std::endl;
  }
  std::cin.getline(line,sizeof(line));
  return 0;
}
like image 869
wu3mei Avatar asked Apr 29 '11 16:04

wu3mei


People also ask

Is deque contiguous memory?

Elements in a deque are not contiguous in memory; vector elements are guaranteed to be. So if you need to interact with a plain C library that needs contiguous arrays, or if you care (a lot) about spatial locality, then you might prefer vector .

Does deque take more memory than vector?

Deque can have additional memory overhead over vector because it's made of a few blocks instead of contiguous one.

Is deque slow?

std deque is surprisingly slow.

Does deque allow random access?

It is to be noted that containers like vector, deque support random-access iterators.


1 Answers

That is correct, pop_front() does not deallocate storage that was allocated by push_back() If you want to deallocate it before the program ends, you can end the lifetime of the object. If you want to deallocate it before the lifetime of the object ends, consider using a "shrink-to-fit" idiom for C++ container classes.

QueueType().swap (deq); // C++98
deq.shrink_to_fit(); // C++11
like image 127
Cubbi Avatar answered Nov 04 '22 05:11

Cubbi