Possible Duplicate:
C programming, why does this large array declaration produce a segmentation fault?
This is my first time here so sorry if I break some rules or if this has been answered before.
I recently made a C program in which I had a matrix of
char buff[NR][1024*1024];
I needed NR = 128. So the program would alocate 128MB. This was in main(). I tried it on a few systems with enough memory with no error on compile. At runtime I recieved segmentation fault on all systems. It worked for NR = 7, but not 8.
I moved that code outside of main making it global. It didn’t crash anymore even for 128.
Does anyone know why this happened?
The compiler was GCC
The problem is you are overflowing the stack which is typically just a few MB in size (the exact size depends on the system and your compiler options). You could allocate the memory on the heap instead using
malloc.