g++ 4.8.1 on Ubuntu can't compile large bitset

2019-05-10 07:52发布

问题:

My source:

#include <iostream>
#include <bitset>

using std::cout;
using std::endl;

typedef unsigned long long U64;
const U64 MAX = 8000000000L;

struct Bitmap
{
  void insert(U64 N) {this->s.set(N % MAX);}
  bool find(U64 N) const {return this->s.test(N % MAX);}
private:
  std::bitset<MAX> s;
};

int main()
{
  cout << "Bitmap size: " << sizeof(Bitmap) << endl;
  Bitmap* s = new Bitmap();
  // ...
}

Compilation command and its output:

g++ -g -std=c++11 -O4  tc002.cpp -o latest 
g++: internal compiler error: Killed (program cc1plus)
Please submit a full bug report,
with preprocessed source if appropriate.
See <file:///usr/share/doc/gcc-4.8/README.Bugs> for instructions.

Bug report and its fix will take long time... Has anybody had this problem already? Can I manipulate some compiler flags or something else (in source probably) to bypass this problem?

I'm compiling on Ubuntu, which is actually VMware virtual machine with 12GB memory and 80GB disk space, and host machine is MacBook Pro:

uname -a
Linux ubuntu 3.11.0-15-generic #23-Ubuntu SMP Mon Dec 9 18:17:04 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux

回答1:

On my machine, g++ 4.8.1 needs a maximum of about 17 gigabytes of RAM to compile this file, as observed with top.

  PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
18287 nm        20   0 17.880g 0.014t    808 D  16.6 95.7   0:17.72 cc1plus

't' in the RES column stands for terabytes ;)

The time taken is

real    1m25.283s
user    0m31.279s
sys     0m5.819s

In the C++03 mode, g++ compiles the same file using just a few megabytes. The time taken is

real    0m0.107s
user    0m0.074s
sys     0m0.011s

I would say this is definitely a bug. A workaround is to give the machine more RAM, or enable swap. Or use clang++.



回答2:

[Comment]

This little thing:

#include <bitset>
int main() {
    std::bitset<8000000000UL> b;
}

results in 'virtual memory exhausted: Cannot allocate memory' when compiled with g++ (Ubuntu/Linaro 4.7.2-2ubuntu1) 4.7.2