0

g++ (MinGW) compiles this code

int main() {
    float test[520073];
}

without any errors, but when I run the executable it crashes. If I lower the number to 520072 it runs normally. When compiling with clang, the exe crashes even with a much shorter array (it crashes starting at a length somewhere between 200,000 and 300,000).

If I change float to double, the number above which it crashes gets about halved, which leads me to believe that the crash has something to do with too much memory being used. However I do not understand why the number is so drastically different between compilers, as sizeof(float) returns 4 on both g++ and clang.

Also, 500,000 seems like a relatively low maximum array length. With floats being 4 bytes in size, it would only take up 2Mb of memory.

What could cause this crash and is there any way I could make larger arrays without the program crashing?

gearmic
  • 47
  • 5
  • 2
    Have you tried increasing the stack size of your program? – Eljay Oct 24 '20 at 17:07
  • 1
    Use a `std::vector test(520073)` or `std::unique_ptr> test = std::make_unique();` instead. – πάντα ῥεῖ Oct 24 '20 at 17:13
  • @πάνταῥεῖ This works (the second suggestion was missing a ```>``` before the ```()``` at the end). Does the fact, that this works and what I tried to do doesn't, have to do with memory being allocated on the heap instead of stack? – gearmic Oct 24 '20 at 18:24
  • 1
    @gearmic _"have to do with memory being allocated on the heap instead of stack?"_ Yes, that's the reason. The stack size is (very) limited, while `std::vector` and `std::unique_ptr` (and `std::shared_ptr`) allocate memory from the "heap". – πάντα ῥεῖ Oct 24 '20 at 18:28

0 Answers0