#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;
}
但是,程序并没有崩溃,而且似乎被阻止了。
这是一个非常典型的内存泄漏程序,但我不知道为什么它没有崩溃。
在你的例子中:
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
或尝试不涉及空检查函数的读取操作。