gpt4 book ai didi

c++ - Linux乐观malloc : will new always throw when out of memory?

转载 作者:IT老高 更新时间:2023-10-28 21:39:57 26 4
gpt4 key购买 nike

我一直在阅读有关 Linux 内存不足的情况,手册页中的以下段落让我思考:

By default, Linux follows an optimistic memory allocation strategy. This means that when malloc() returns non-NULL there is no guarantee that the memory really is available. This is a really bad bug. In case it turns out that the system is out of memory, one or more processes will be killed by the infamous OOM killer. [...]

考虑到 operator new 实现最终会在某个时候调用 malloc,是否有任何保证 new 会在 Linux 上实际抛出?如果没有,如何处理这种明显无法检测到的错误情况?

最佳答案

视情况而定; you can configure the kernel's overcommit settings使用 vm.overcommit_memory。

Herb Sutter 几年前讨论过 this behavior is actually nonconforming to the C++ standard :

"On some operating systems, including specifically Linux, memory allocation always succeeds. Full stop. How can allocation always succeed, even when the requested memory really isn't available? The reason is that the allocation itself merely records a request for the memory; under the covers, the (physical or virtual) memory is not actually committed to the requesting process, with real backing store, until the memory is actually used.

"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)."

关于c++ - Linux乐观malloc : will new always throw when out of memory?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1655650/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com