问题描述
我一直在阅读有关 Linux 内存不足的情况,手册页中的以下段落让我想到了:
I have been reading about out of memory conditions on Linux, and the following paragraph from the man pages got me thinking:
默认情况下,Linux 遵循乐观的内存分配策略.这意味着当 malloc() 返回非 NULL 时,不能保证内存确实可用.这是一个非常糟糕的错误.如果发现系统内存不足,臭名昭著的 OOM 杀手将杀死一个或多个进程.[...]
考虑到操作符 new 实现最终会在某个时候调用 malloc,是否有任何保证 new 会真正投到 Linux 上?如果没有,如何处理这种明显无法检测的错误情况?
Considering that the operator new implementation will end up calling malloc at some point, are there any guarantees that new will actually throw on Linux? If there aren't, how does one handle this apparently undetectable error situation?
推荐答案
视情况而定;您可以使用 vm.overcommit_memory 配置内核的过载设置.
Herb Sutter 几年前讨论过 这种行为实际上不符合 C++ 标准:
Herb Sutter discussed a few years ago how this behavior is actually nonconforming to the C++ standard:
"在某些操作系统上,特别是 Linux,内存分配总是成功的.句号.即使请求的内存确实不可用,分配如何总是成功?原因是分配本身只是记录了对内存的请求;在幕后,(物理或虚拟)内存实际上并未提交给请求进程,具有真正的后备存储,直到内存被实际使用.
"请注意,如果 new 直接使用操作系统的设施,那么 new 将总是成功,但任何后来的无害代码如 buf[100] = 'c';可以抛出或失败或停止.从标准 C++ 的角度来看,这两种效果都不符合标准,因为 C++ 标准要求如果 new 不能提交足够的内存,它必须失败(这不会),并且像 buf[100] = 'c' 这样的代码应该'不抛出异常或以其他方式失败(这可能)."
"Note that, if new uses the operating system's facilities directly, then new will always succeed but any later innocent code like buf[100] = 'c'; can throw or fail or halt. From a Standard C++ point of view, both effects are nonconforming, because the C++ standard requires that if new can't commit enough memory it must fail (this doesn't), and that code like buf[100] = 'c' shouldn't throw an exception or otherwise fail (this might)."
这篇关于Linux 乐观 malloc:内存不足时 new 总是会抛出吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!