#include <stdio.h> #define N 1024 int main(){ int i, j; int a[N][N]; int b[N][N]; for (i=0;i<N;i++){ a[i][i]=i; b[i][i]=i; } for (i=0;i<N;i++) for(j=0;j<N;j++) { printf("%d", a[i][j]); printf("%d", b[i][j]); } return 0; }
This program is a reason of segmentation fault, but if I define N as 1023, program will work correctly. Why it happens?
Check shell limits Usually it is the limit on stack size that causes this kind of problem. To check memory limits, use the ulimit command in bash or ksh , or the limit command in csh or tcsh . Try setting the stacksize higher, and then re-run your program to see if the segfault goes away.
A space that is not allocated to you but you try to access it anyway. You cannot get in. In other words, it gives an error. The same way if at any point in a program, memory space that is not allocated to a particular variable or code block is accessed a segmentation fault occurs, also called the core dump error.
Use a #define or the sizeof operator at all places where the array length is used. Improper handling of NULL terminated strings. Forgetting to allocate space for the terminating NULL character. Forgetting to set the terminating NULL character.
Dereferencing or assigning to an uninitialized pointer (wild pointer, which points to a random memory address) Dereferencing or assigning to a freed pointer (dangling pointer, which points to memory that has been freed/deallocated/deleted) A buffer overflow. A stack overflow.
You are overflowing the stack. 2 * 1024 * 1024 * sizeof(int)
is a lot for most systems.
The simplest solution would be to make the arrays static
.
static int a[N][N]; static int b[N][N];
Other methods:
Use malloc
in a loop and of course remember to free
int **a = malloc(N * sizeof *a); for (i = 0; i < N; i++) a[i] = malloc(N * sizeof *a[i]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With