为什么我的程序在内存不足时偶尔会出现段错误而不是抛出 std::bad_alloc?
我有一个程序,它实现了几种启发式搜索算法和几个领域,旨在通过实验评估各种算法。该程序用C++编写,使用GNU工具链构建,并在64位Ubuntu系统上运行。当我运行实验时,我使用 bash 的 ulimit 命令来限制进程可以使用的虚拟内存量,以便我的测试系统不会开始交换。
某些算法/测试实例组合达到了我定义的内存限制。大多数时候,程序会抛出 std::bad_alloc 异常,该异常由默认处理程序打印,此时程序终止。有时,程序不会发生这种情况,而只是出现段错误。
为什么我的程序在内存不足时偶尔会出现段错误,而不是报告未处理的 std::bad_alloc 并终止?
I have a program that implements several heuristic search algorithms and several domains, designed to experimentally evaluate the various algorithms. The program is written in C++, built using the GNU toolchain, and run on a 64-bit Ubuntu system. When I run my experiments, I use bash's ulimit
command to limit the amount of virtual memory the process can use, so that my test system does not start swapping.
Certain algorithm/test instance combinations hit the memory limit I have defined. Most of the time, the program throws an std::bad_alloc exception, which is printed by the default handler, at which point the program terminates. Occasionally, rather than this happening, the program simply segfaults.
Why does my program occasionally segfault when out of memory, rather than reporting an unhandled std::bad_alloc and terminating?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
原因之一可能是默认情况下 Linux 会过度使用内存。从内核请求内存似乎工作正常,但稍后当您实际开始使用内存时,内核会注意到“哦,糟糕,我内存不足”,调用内存不足(OOM)杀手,它会选择一些受害者进程并杀死它。
有关此行为的说明,请参阅 http://lwn.net/Articles/104185/
One reason might be that by default Linux overcommits memory. Requesting memory from the kernel appears to work alright, but later on when you actually start using the memory the kernel notices "Oh crap, I'm running out of memory", invokes the out-of-memory (OOM) killer which selects some victim process and kills it.
For a description of this behavior, see http://lwn.net/Articles/104185/
可能是某些代码使用了 no-throw new 并且不检查返回值。
或者某些代码可能捕获异常但不处理它或重新抛出它。
It could be some code using no-throw new and not checking the return value.
Or some code could be catching the exception and not handling it or rethrowing it.
詹尼布说的话。事实上,Linux 默认情况下从不抛出 std::bad_alloc (或从 malloc() 返回 NULL)。
What janneb said. In fact Linux by default never throws std::bad_alloc (or returns NULL from malloc()).