Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation Fault, large arrays

Tags:

#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?

like image 691
Alexey Matveev Avatar asked Oct 26 '11 11:10

Alexey Matveev


People also ask

How do I find out what is causing my segmentation fault?

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.

What is segmentation fault C++ array?

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.

How can segmentation fault be avoided?

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.

What are three kinds of pointers that can cause a segmentation fault?

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.


1 Answers

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:

  • Make the arrays global (this is essentially the same as the above)
  • 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]); 
like image 125
cnicutar Avatar answered Sep 26 '22 21:09

cnicutar