以下代码不会引发异常并打印“成功”。为什么?
#include <iostream>
int main()
{
size_t size = size_t(1024)*1024*1024*1024*1024*1024*1024*1024;
char* data = new char[size];
if (data == NULL)
std::cout << "fail" << std::endl;
else
std::cout << "success" << std::endl;
return 0;
}
- 编译器:g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
- 操作系统:Ubuntu 12.04
- 内存:8 GB
如果这就是它的工作方式,我如何检查我是否有足够的内存?
[编辑: 让我的愚蠢代码更加正确,现在如果我删除两个 *1024
]
最佳答案
我的编译器可以回答这个问题:
$ g++ --version
g++ (GCC) 4.7.1 20120721 (prerelease)
Copyright (C) 2012 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
$ g++ -Wall -Wextra -pedantic q12507456.c++
q12507456.c++: In function 'int main()':
q12507456.c++:5:42: warning: integer overflow in expression [-Woverflow]
$
关于c++ - 为什么 2^80 字节的内存分配不会失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12507456/