-4

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 ?

Himanshu
  • 4,327
  • 16
  • 31
  • 39
Radu93
  • 21
  • 1
  • 1
    Pick a language, don't ask for C and C++ at the same time. Although the underlying problem may be the same in both languages, the proper way to solve it most definitely isn't. –  Apr 13 '16 at 10:03
  • rep-PersonalServicesWorker fodder. – Martin James Apr 13 '16 at 10:40

2 Answers2

3

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

Lundin
  • 195,001
  • 40
  • 254
  • 396
marcinj
  • 48,511
  • 9
  • 79
  • 100
  • You should probably emphasize the size of the stack is not defined by the language standard (neither C nor C++). – barak manos Apr 13 '16 at 10:12
1

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.

rcgldr
  • 27,407
  • 3
  • 36
  • 61
  • 1
    "The matrix needs to be allocated from the heap" - not necessarily. That depends on the size of the stack, as defined in the project linker settings (and which is completely agnostic to both language standards - C **and** C++). Although your proposal may solve the problem on OP's specific configuration, it is not a generally correct answer. – barak manos Apr 13 '16 at 10:09
  • @barakmanos - The OP specifically mentioned stack overflow. My answer was in response to the OP's question. As you mentioned, the alternative would be to increase the stack size via a compiler option, if the OP's compiler has that option. I updated my answer. – rcgldr Apr 13 '16 at 21:19