简体   繁体   中英

Does MS Stl library contain a memory leak?

I came across the web (don't recall where) a note that says that MS c++ stl containers have a memory leak in their clear() API.

Therefore if you have a:

void main()
{ 
   std::vector<int> vVec;
   for(int i =0; i < 100; i++)
      vVec.push_back(i);

   vVec.clear();
}

Therefore the memory allocated on the heap for the vector is not really released...

The note said (as far as i recall) the following technique to make sure the memory is really released...

void main()
{ 
   std::vector<int> vVec;
   for(int i =0; i < 100; i++)
      vVec.push_back(i);

   vVec.clear();
   vector<int>(vVec).swap(vVec);
}

Do you have experience with such? is the above true? and if yes, what actually happening here?

(and last question, sorry, is this true for all other stl containers?) Thanks,

It's not a memory leak; it's the required behavior (by the standard). std::vector<>::clear() is not allowed to lower the capacity, and thus cannot free its buffer. The memory will be freed when the destructor is called, and in swap , the buffers will be swapped, so in

vector<int>().swap(vVec);

, the temporary object gives vVec its (empty) buffer, and receives the non-empty buffer of vVec , which it deletes at the end of the full expression.

This is normally not needed, or even wanted, after clear ; if you want a completely new vector, just declare one. On the other hand, if you've been filling a vector gradually, it could easily have a capacity of more than is needed, and an excessively large buffer. In this case:

vector<int>(vVec).swap(vVec);

will first make a (temporary) copy with an exactly sized buffer, then swap buffers with vVec . The results will be that vVec has a capacity equal to its size, and no more. (Formally, this isn't guaranteed by the standard anywhere, but in practice, it corresponds to all of the implementations I know of.)

std::vector<> is allowed to allocate more memory than is required (this is necessary to make it possible to append elements in amortized constant time).

clear() is not obliged (in fact, not allowed) to release the memory that's been allocated for the elements.

However, I would not call the above behaviours memory leaks since the memory will get correctly released when the vector goes out of scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM