2

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

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

3 Comments

but I need 11-dimensional array and C has no new[] operand
You mean use malloc() - this is a C question, not C++.
@Ant: sorry, fixed it. @Norma: why would you need that in the first place?! You can simulate it (I'll add that in), or use an int*******... but seriously speaking you probably have a design flaw.
1
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

Comments

1

The size of your array is 3^10 * 8 * sizeof(int). Assuming a 32 bit int, sizeof(int) is four bytes and the size of your array is:

3^10 * 8 * 4 = 1,889,568 bytes

So you're stack isn't that big and you're overflowing the stack.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.