The fast answer of why vector might crash and not deque is that because vector uses a contiguous buffer you'll bad_alloc "quicker". And also on a request that asks for a large chunk.
Why? Because it is less likely that you will be able to allocate a contiguous buffer than a smaller one.
vector
will allocate a certain amount and then try a big "realloc" for a bigger buffer. It might be possible to extend the current memory space but it might not, and may need to find a whole new chunk of memory.
Let's say it looks to expand by a factor of 1.5. So you currently have 40% of the memory available in your vector in use and it needs to find 60% of the memory available but cannot do it at the current location. Well that takes you to the limit so it fails with bad_alloc
but in reality you are only using 40% of the memory.
So in reality there is memory available and those operating systems that use "optimistic" memory allocation will not accidentally over-allocate for you. You've asked for a lot and it couldn't give it to you. (They are not always totally optimistic).
deque
on the other hand asks for a chunk at a time. You will really use up your memory and as a result it's better to use for large collections, however it has the downside that when you run out of memory you really do run out. And your lovely optimistic memory allocator cannot handle it and your process dies. (It kills something to make more memory. Sadly it was yours).
Now for your solution of how to avoid it happening? Your answer might be a custom allocator, i.e. the 2nd parameter of deque, which could check the real system memory available and refuse to allocate if you have hit a certain threshold.
Of course it is system dependent but you could have different versions for different machines.
You could also set your own arbitrary "limit", of course.
Assuming your system is Linux, you might be able to turn overcommit off with
'echo 2 > /proc/sys/vm/overcommit_memory'
You would need root (admin) permissions to do that. (Or get someone who has it to configure it that way).
Otherwise, other ways to examine the memory usage are available in the Linux manuals, usually referred to in /proc
.
If your system isn't Linux but another that over-commits, you'll have to look up how you can by-pass it by writing your own memory manager. Otherwise take the simpler option of an arbitrary configurable maximum size.
Remember that with deque
your allocator will only be invoked when you need to allocate a new "chunk" and not for every push_back
.