Segmentation Fault when instantiating a class two times

  arrays, c++, segmentation-fault, std

I am porting a C algorithm to C++. The original algorithm relies a lot on arrays, and I am porting them as is using std::array.

#include <array>


class Point
{
private:
    float x{};
    float y{};
    float z{};
public:
    Point() = default;
};

class B
{
private:
    std::array<Point, 25000> array_of_Point{};
public:
    B() = default;
};

class A
{
private:
    std::array<B, 10> array_of_B{};
    std::array<Point*, 250000> array_of_pointers{};
public:
    A() = default;
};

int main(int argc, char** argv)
{
    A sceneA{};
    A sceneB{};

    return 0;
}

If only one instance of A is created, the code works as expected. The Segmentation Fault occurs in the first brace after the main definition when trying to instance two or more classes. Valgrind only inform about a "Invalid write of size 4" at that brace.

The sizeof(A) returns ~6,5MB. My guess is that the memory amount in the stack is not enough to store two A instances. Nevertheless, the C code using raw arrays works flawlessly. I want to understand what is happening exactly.

The execution fails when compiling using g++ 11.1.0 with -O0 flag

Source: Windows Questions C++

LEAVE A COMMENT