Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C -multidimensional array causes Segmentation Fault (GCC)

Tags:

arrays

c

gcc

Why if I change the size of one of the dimensionality of an array I get a run-time Error: "Segmentation Fault?". Example:

#include <stdio.h>
#define DIM 8 
int main(int argc, char **argv)
{
    int a[3][3][3][3][3][3][3][3][3][3][DIM],
        b;
    a[1][1][1][1][1][1][1][1][1][1][1] = 2;
    b=a[1][1][1][1][1][1][1][1][1][1][1];
    printf("%d \n",b);
    return 0;
}

If DIM is 8 it generated no run-time error, but just if DIM is greater than 8, it causes run-time Error "Segmentation Fault". Why ???

like image 945
psihodelia Avatar asked May 09 '26 17:05

psihodelia


2 Answers

Almost certainly a stack overflow. You are allocating, what, 3 ^ 10 * 9 * sizeof(int) bytes! Use int *a = (int*)malloc(N * sizeof(int)) instead, where N is the number of ints you want. Then you can simulate an N-dimensional array on it.

I'll explain how to simulate a 2D array on a 1D array.. Say it has rows of width 10. Then you access the 5th value on row three by taking a[10 * 2 + 5]. In general, you do a[width * (row - 1) + column].

Second method. You can allocate an array of pointers to pointers of ints:

int **a = (int**)malloc(rows * sizeof(int*))
for (int i=0; i<row; ++i)
    a[i] = (int*)malloc(columns * sizeof(int))

... extending this to more dimensions left as an exercise for the reader.

like image 76
int3 Avatar answered May 12 '26 07:05

int3


3*3*3*3*3*3*3*3*3*3*8 = 472392; 472392*4 /* sizeof (int) */ = 1889568
3*3*3*3*3*3*3*3*3*3*9 = 531441; 531441*4 /* sizeof (int) */ = 2125764

I guess your stack is limited to 2Mbytes

like image 28
pmg Avatar answered May 12 '26 07:05

pmg