Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why memory allocation of 2^80 bytes doesn't fail?

Following code doesn't throw exception and prints "success". Why ?

#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;
}
  • Compiler: g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
  • OS: Ubuntu 12.04
  • RAM: 8 GB

And if this is how it's meant to work, how do I check that I have enough memory ?

[Edit: made my stupid code a bit more correct, now it would at least fail on x64 if I remove two *1024]

like image 290
Alexander Malakhov Avatar asked Sep 20 '12 06:09

Alexander Malakhov


2 Answers

My compiler can answer this one:

$ 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]
$
like image 131
R. Martinho Fernandes Avatar answered Sep 24 '22 09:09

R. Martinho Fernandes


This is more than likely to be the fact that the number you are requesting is too large to be stored within an integer and you are experiencing overflow here and the memory allocated is in fact far far less than you think it is.

Here 2^80 = 1208925819614629174706176 according to http://en.wikipedia.org/wiki/Yobibyte

like image 24
mathematician1975 Avatar answered Sep 25 '22 09:09

mathematician1975