0

Here is my code where I declare a 2d array of size 2048 x 2048

#include <stdio.h>

int main(void)
{   
    int src[2048][2048];
    
    return 0;
}

I am on Windows 11 machine with Cygwin installed. When I run gcc, the code compiles, but when I run a.exe, I get the following error.

0 [] a 1717 cygwin_exception::open_stackdumpfile: Dumping stack trace to a.exe.stackdump

But, if I declare a global array of the same size outside main function, and run the a.exe, I do not get any error

#include <stdio.h>

int src[2048][2048];

int main(void)
{   
    
    
    return 0;
}

What could be happening here ? I have read few other posts here suggesting that large arrays should be created on heap using malloc. In fact, if I use malloc inside the function, I do not get any compile or runtime errors.

#include <stdio.h>
#include <stdlib.h>

int main(void)
{   
    int r = 2048, c = 2048;
 
    int* ptr = malloc((r * c) * sizeof(int));

    for (int i = 0; i < r * c; i++)
        ptr[i] = i + 1;

    free(ptr);
    
    return 0;
}

Thanks!

user9026
  • 852
  • 2
  • 9
  • 20
  • 3
    Local variables, including arrays, are usually stored on the process stack. The stack is a limited resource, on Linux it's usually 8 MiB, on Windows only one single MiB. Your array is 16 MiB (assuming the common 4-byte `int`). That just won't fit. Do you *really* need an array of that size? What is it to be used for? What is the actual and underlying problem your array is supposed to solve? – Some programmer dude Jul 06 '23 at 07:59
  • @Some programmer dude, I am reading book, "Computer Systems: A programmers Perspective" and there is some code, where the author is discussing some problem about how arrays are processed (row wise vs columnwise). I got runtime errors, so I was just curious. So, the way to go here would be using malloc or using Big Data technologies I suppose – user9026 Jul 06 '23 at 08:09
  • 2
    Just use malloc instead and you should be good to go. `int (*src)[2048] = malloc( sizeof(int[2048][2048]) );` – Lundin Jul 06 '23 at 10:02
  • You could also specify a larger stack as a linker option. – stark Jul 06 '23 at 11:25
  • just make it `static` – Pignotto Jul 06 '23 at 11:37

0 Answers0