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

Ale*_*hov 16 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;
}
Run Code Online (Sandbox Code Playgroud)
  • 编译器:g ++(Ubuntu/Linaro 4.6.3-1ubuntu5)4.6.3
  • 操作系统:Ubuntu 12.04
  • RAM:8 GB

如果这是它的工作方式,我如何检查我有足够的内存?

[ 编辑:让我的愚蠢代码更正确,现在如果我删除两个,它至少会在x64上失败*1024]

R. *_*des 20

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

$ 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]
$
Run Code Online (Sandbox Code Playgroud)


mat*_*975 6

这很可能是因为您请求的数字太大而无法存储在整数中,并且您在这里遇到溢出并且分配的内存实际上远远低于您的想象.

根据http://en.wikipedia.org/wiki/Yobibyte,这里有2 ^ 80 = 1208925819614629174706176


小智 5

1024*1024*1024*1024*1024*1024*1024*1024
Run Code Online (Sandbox Code Playgroud)

计算时会导致整数溢出 - 也就是说,它将取模2 ^ 32(或2 ^ 64,具体取决于您的系统),并且这是可以分配的零字节.