Intermittent segmentation faults with straightforward C++ program

1.5k views Asked by At

I'm currently working through Thinking in C++, and chapter 9, exercise 15 gives instructions to time the difference between inline and non-inline constructors. In doing so, I created a metric shedload of object instances in an array, but when I get up to a certain point, the program begins segfaulting intermittently. I'm not doing anything peculiar, and the number doesn't seem to be magical (close to a power of 2 or anything), so it strikes me as very strange. Indeed, the objects are all very small, containing a single integer.

I'm not using any custom compilation or optimization options, and using standard g++ (not icc or anything).

I'm stumped as heck by this, in what should be a straightforward program. Any insight would be appreciated, as even the strace output (below) doesn't give me any hints.

Thank you in advance.

ex15.cc:

#include <ctime>
#include <iostream>
using namespace std;

class A
{
    static int max_id;
    int id;
public:
    A() { id = ++max_id; }
};
int A::max_id = 0;

class B
{
    A a;
public:
    B() {}
};

int main()
{
    clock_t c1, c2;
    cout << "Before" << endl;
    c1 = clock();
    B b[2093550];   // intermittent segfault around this range
    c2 = clock();
    cout << "After; time = " << c2 - c1 << " usec." << endl;
    getchar();
}

Run log:

$ ./ex15
Before
After; time = 40000 usec.
$ ./ex15
Segmentation fault
$ ./ex15
Before
After; time = 40000 usec.
$ ./ex15
Segmentation fault
$ ./ex15
Before
After; time = 40000 usec.
$ ./ex15
Before
After; time = 40000 usec.
$ ./ex15
Segmentation fault

The strace output shows it dying here:

mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7
f93000
--- SIGSEGV (Segmentation fault) @ 0 (0) ---
+++ killed by SIGSEGV +++

And from a successful run:

mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7
f4c000
write(1, "Before\n", 7)                 = 7
times({tms_utime=0, tms_stime=0, tms_cutime=0, tms_cstime=0}) = -1160620642
times({tms_utime=4, tms_stime=0, tms_cutime=0, tms_cstime=0}) = -1160620637
write(1, "After; time = 40000 usec.\n", 26) = 26
fstat64(0, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 0), ...}) = 0
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7
f4b000
read(0, "\n", 1024)                     = 1
munmap(0xb7f4c000, 4096)                = 0
exit_group(0)                           = ?
2

There are 2 answers

4
Peter Huene On BEST ANSWER

If sizeof(B) is 4 bytes, that puts the size of that array (b) at 8374200 bytes. That's pretty close to what I'm guessing is your default maximum thread stack size of 8 MiB (8388608 bytes). So it looks like you're overflowing your stack.

2
sth On

Allocating an array of 2093550 B objects on the stack most probably causes a stack overflow. Dynamically allocate it with new to avoid the segmentation fault.