What is the most common reason that “bad_alloc” is thrown?

邮差的信 提交于 2020-04-10 18:05:26

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/50827678/what-is-the-most-common-reason-that-bad-alloc-is-thrown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!