Search code examples
c++c++11bad-alloc

What is the most common reason that "bad_alloc" is thrown?


Is there a more frequent error that is memory-related that throws bad_alloc? I understand that it means that memory-allocation has failed, but what is the most common mistake that leads to this in code?


Solution

  • EDIT: The other commenters have pointed out a few interesting scenarios. I'm adding them to my response for the sake of completeness.

    Case 1: Running out of memory

    My understanding is that bad_alloc is thrown whenever the operators new and new[] fail to allocate memory to an object or variable. This can happen if you've newed a bunch of objects and forgot to delete them before they got out of scope (i.e., your code leaks like crazy).

    Case 2: Allocating huge amounts of memory in one swoop

    Allocating a large chunk of memory, as in the case of a 1000 x 1000 x 1000 matrix of doubles, will possibly fail because it requires a single block of that size.

    There might be several free memory blocks available, but none of these are large enough.

    Case 3: Passing an invalid value to new[]

    bad_alloc is thrown if you pass a negative value as its parameter.