I am using Visual Studio 2015 and when I declare a matrix like this
double m[500][500];
I get stack overflow, before reaching the first line of code from function main.
Is there not enough memory ? What to do ?
I am using Visual Studio 2015 and when I declare a matrix like this
double m[500][500];
I get stack overflow, before reaching the first line of code from function main.
Is there not enough memory ? What to do ?
Because such matrix requires ~2MB of stack memory and stack mostly is only 1MB, so you get stack overflow. Stack memory size can be changed in your linker options (or when creating thread - at least under WinAPI - Windows), it is not defined in language standard. Even if you setup a stack size example: 3MB, you never know how much of it is available - your code execution might be deep inside some function calls which also use stack memory for their variables.
Solution is to use dynamic memory (heap) - std::vector (for C++):
// Allocates one memory buffer on heap, automatically manages memory.
std::vector<double> m(500*500,0);
m[499 + 499 * 500]=12;
// Not very efficent, as it allocated 500 memory buffers for each row,
// your memory will not be alligned what might cause cache misses
std::vector<std::vector<double>> m2(500, std::vector<double>(500));
m2[499][499]=12;
or:
double * m = (double *) malloc (500*500*sizeof(double));
m[x + y * 500] = 1;
free(m);
in case you want this under C, which would work also under C++ but would be discouraged
The matrix needs to be allocated from the heap. For C use malloc, for C++, use new. If your compiler has an option to use a larger stack size, that would be an alternative.