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?
These are variable length arrays (VLA), as
Nis not a constant expression. The const-ness in the parameter only ensures thatNis read-only. It doesn’t tell the compiler thatNis 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
-pedanticoption, 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::vectoras: