简体   繁体   中英

is there memory leak when STL throws a “bad_alloc” exception?

I have a program that using STL to use big containers of numbers, sometimes vector , sometimes deque ; sometimes it constructing a big vector directly, sometimes it starts with a small size then enlarges using resize .

The vector or deque constructor or resize sometimes throws a "bad_alloc" exception. My question is, is there memory leak here? If there's no memory leak, I might still continue; but if there is , things are more troublesome.

My system is Windows 7 64-bit, Visual Studio 2013, and working on 32-bit programs.

No.

A thrown std::bad_alloc exception does not mean there is a memory leak. It means that dynamic allocation using operator new or operator new[] has failed.

Default allocators used by the standard container types ( std::Vector , std::list , etc) typically use operator new or new[] , so can also throw a std::bad_alloc if they fail.

A memory leak is just one possible cause of memory exhaustion and, in turn, memory exhaustion is only one possible cause of a failure to dynamically allocate memory using new or new[] .

Generally speaking, if std::bad_alloc is thrown, it means an attempt to allocate memory has failed (and does not need to be deallocated). So there is no leak. If some object (or class) is poorly implemented, it might cause a memory leak if an exception is thrown. The standard describes requirements of the standard containers that prevent that, assuming the elements of the vector also provide suitable guarantees.

std::bad_alloc is thrown when new or new[] fails to allocate memory.

You may have run out of main memory? You may have have tried to allocate a particularly structure new int[1024*1024*1024]; ? Your heap may have become fragmented (Many allocations and deletions), So a continuous space of memory of the size that you want couldn't be allocated.

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