Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does clear() in std::vector generates a memory leak?

My question is pretty much an extension of this one: Is std::vector memory freed upon a clear?

Here people explained that the memory allocated for the elements of a std::vector is not released after calling clear(). But will this memory be free for the OS to allow other programs to use it or will it be available for my program to use it anywhere else?

If not (if the memory continues to be allocated only for this vector and I can't access it anymore) isn't it a memory leak like the ones we have with pointers? Then clear() when used alone like this would be totally unsafe right?

I would be happy if someone could clarify me in this one. Thanks.


1 Answers

Does clear() in std::vector generates a memory leak?

No.

But will this memory be free for the OS to allow other programs to use it or will it be available for my program to use it anywhere else?

OS can swap the memory to disk, to allow other programs to use the physical memory.

if the memory continues to be allocated only for this vector and I can't access it anymore

You can reuse the memory by adding new objects into the vector. Or release it by destroying the vector. The destructor absolutely guarantees to free the memory.

isn't it a memory leak like the ones we have with pointers?

No. A memory leak happens when the pointer to the memory is lost. But in this case the vector safely keeps track of the pointer, and frees it when it is destroyed.

Then clear() when used alone like this would be totally unsafe right?

clear isn't inherently unsafe, but the assumption that it will free the memory may be.

like image 111
eerorika Avatar answered Apr 30 '26 00:04

eerorika



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!