c++ - 为什么 2^80 字节的内存分配不会失败?

标签 c++ memory-management

以下代码不会引发异常并打印“成功”。为什么?

#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]

,它至少会在 x64 上失败

最佳答案

我的编译器可以回答这个问题:

$ 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/

相关文章:

android - 当 Android 应用程序崩溃时,我可以获得 C++ 堆栈跟踪吗?

c++ - 公共(public)函数/类及其相应头文件的列表

c++ - 为什么 Visual Studio 2013 会发出 C4996 错误?

c++ - 关于删除节点

c++ - 如何重构具有大量 std::cin 和 std::cout 操作的程序?

c - 如何为我的 php 扩展调试 'zend_mm_heap corrupted'

linux - kmalloc如何返回大于物理地址大小的物理地址?

c++ - 临时字符串的内存分配

c - 为什么 Valgrind 在错误的地方给出错误?

c++ - 位图边界矩形算法 C++