1

When I compile this code with clan g++ main.cpp && ./a.out I get a segfault (terminated by signal SIGSEGV (Adressbereichsfehler)).

gcc-Version 9.3.0
clang version 9.0.1

Run with Coliru here

#include <random>

struct Abra
{
  float hagrid[3000000];

  std::random_device voldemort{};
};

int main()
{
  Abra harry = {};
  return 0;
}

Why is that and how can I fix this? What I tried is to switch the declaration order of hagrid and voldemort but it still segfaults (Coliru example)

Darius Duesentrieb
  • 837
  • 10
  • 20
  • 1
    `hagrid` is too big to be stored on stack, > 11 MB. Use `vector` or allocate memory on heap by `new`. – rafix07 Apr 20 '20 at 13:46
  • Allocating ~12MB on the stack might not be the best thing to do and can cause issues – Sami Kuhmonen Apr 20 '20 at 13:46
  • Comment out `voldemort` line, and your example still crashes. The issue has absolutely nothing to do with `std::random_device` – Igor Tandetnik Apr 20 '20 at 13:47
  • You should be able to increase the size of your stack. You'll need to refer to your compiler's documentation. On my one machine, the stack by default is 64 kB. I'd have to change that to 16 MB to be able to handle the very large struct Abra. – Eljay Apr 20 '20 at 13:49
  • @SamiKuhmonen Are there other issues with big arrays on the stack other than the stack size? I tend to just use something like `-fsplit-stack` for gcc or increasing the stack size with other techniques. – Darius Duesentrieb Apr 20 '20 at 14:14

1 Answers1

2

Why does a std::random_device class member cause a segfault?

Because your class is too big to fit on the stack, so when you create an instance in automatic storage, you overflow the stack (how appropriate; see the name of this website).

The hagrid array is about 11.4 mega bytes (may depend on CPU architercutre), and the default stack size on most desktop systems is about 1 to 8 mega bytes.

how can I fix this?

Use dynamic storage for large objects. Simplest way to create a dynamic array is std::vector.

eerorika
  • 232,697
  • 12
  • 197
  • 326