0

I have the following code

#include <stdio.h>
//#define arraySize 5
#define arraySize 500
void func(double B[arraySize][arraySize])
{
    B[0][0] = 5;
}

int main(void) {
    double Ar2D[arraySize][arraySize];
    func(Ar2D);
    printf("%f", Ar2D[0][0]);
}

Code works fine when I test it in a linux virtual machine, but when I run it in minGW, it crashes if I set arraySize to 500 (works fine in minGW if I set arraySize to 5). What is the best way to fix this?

  • 1
    Do not put the array in stack, that's the way. Easy alternative: Make it global variable, since size is compile time constant. – hyde Apr 28 '22 at 15:36
  • The default stack size on Linux is 8Mib and on Windows it's only 1Mib if I remember correctly. Best is not using huge local variables. Either make it static or global. – Jabberwocky Apr 28 '22 at 15:40
  • Does this answer your question? [Increase stack size when compiling with mingw?](https://stackoverflow.com/questions/3557691/increase-stack-size-when-compiling-with-mingw) – Retired Ninja Apr 28 '22 at 16:01

1 Answers1

0

You really should avoid using the stack for large things.

It's also a security risk as stack overflows wan be abused by hackers (e.g. to try to attempt running arbitrary code).

Better is to use the heap, you can do this by replacing

double Ar2D[arraySize][arraySize];

with

double** Ar2D = (double**)malloc(arraySize * arraySize * sizeof(double));

and of course don't forget to free(Ar2D);

Brecht Sanders
  • 6,215
  • 1
  • 16
  • 40