为什么内存泄漏程序不会崩溃(被oom_killer杀死)?

问题描述 投票:0回答:1
  • 我写了一个典型的内存泄漏程序,我想测试一下它是否会被oom_killer杀死。
#include <stdlib.h>
#include <iostream>

constexpr size_t kBytes = 1 << 30;  // 1G bytes

int main () {
  std::cout << kBytes << std::endl;
  int cnt = 0;
  while (true) {
    char* p = static_cast<char*>(malloc(kBytes));
    std::cout << ++cnt << "," << "addr of p is :" << p << std::endl;
  }
  return 0;
}

但是,程序并没有崩溃,而且似乎被阻止了。

  • cnt的最后一次迭代值为131063。
  • 内存消耗不再增长。

The output of the program

The result of the top command

这是一个非常典型的内存泄漏程序,但我不知道为什么它没有崩溃。

c++ memory-leaks
1个回答
0
投票

在你的例子中:

    只要分配成功,
  • p
    就具有非零值。
  • 一旦可用内存耗尽,
  • p
    将具有空值。

一旦内存耗尽,您就假设在读取

p
的空指针值时会发生内存访问冲突。

如果我创建一个将 null 值传递给

std::ostream
operator <<
:

的更简单示例
#include <iostream>

int main()
{
        char *psz = nullptr;

        std::cout << "Value of string is: " << psz << std::endl;

        return 0;
}

我得到简单的输出:

Value of string is: 

虽然两个示例都传递空指针,但会进行检查,以便如果

std::ostream::write
参数为空,则
__s
仅写入空字符串。

要引发内存访问冲突,请尝试写入

p
或尝试不涉及空检查函数的读取操作。

© www.soinside.com 2019 - 2024. All rights reserved.