bad_alloc
comes from heap problems of some kind, and can be thrown by any code that indirectly allocates or frees heap memory, which includes all the standard library collections (std::vector
, std::map
, etc) as well as std::string
.
If your programs do not use a lot of heap memory (so they're not running out of heap), bad_alloc
s are likely caused by heap corruption, which is generally caused by using dangling pointers into the heap.
You mention that your code does a lot of resize
operations -- resize
on most collections will invalidate all iterators on the collection, so if you reuse any iterator after a resize
, that may cause heap corruption that manifests bad_alloc
exceptions. If you use unchecked vector element accesses (std::vector::operator[]
), and your indexes are out of range, that can cause heap corruption as well.
The best way to track down heap corruption and memory errors in general is to use a heap debugger such as valgrind