Detecting that the stack is full

c++, segmentation-fault, stack, stack-overflow

Solution

float data_1[N*N];
float data_2[N*N];

These are variable length arrays (VLA), as `N` is not a constant expression. The const-ness in the parameter only ensures that `N` is read-only. It doesn't tell the compiler that `N` is constant expression.

VLAs are allowed in C99 only; in other version of C, and all versions of C++ they're not allowed. However, some compilers provides VLA as compiler-extension feature. If you're compiling with GCC, then try using `-pedantic` option, it will tell you it is not allowed.

Now why your program gives segfault, probably because of stack-overflow due to large value of `N * N`:

Consider using `std::vector` as:

#include <vector> 

void fun(const unsigned int N) 
{
  std::vector<float> data_1(N*N);
  std::vector<float> data_2(N*N);

  //your code
}

Problem

When writing C++ code I've learned that using the stack to store memory is a good idea. But recently I ran into a problem: I had an experiment that had code that looked like this: ``` void fun(const unsigned int N) { float data_1[N*N]; float data_2[N*N]; /* Do magic */ } ``` The code exploted with a seqmentation fault at random, and I had no idea why. It turned out that problem was that I was trying to store things that were to big on my stack, is there a way of detecting this? Or at least detecting that it has gone wrong?

Original source