简体   繁体   English

C多维数组导致分段错误(GCC)

[英]C -multidimensional array causes Segmentation Fault (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". 如果DIM为8,则不会产生运行时错误,但只要DIM大于8,就会导致运行时错误“Segmentation Fault”。 Why ??? 为什么???

Almost certainly a stack overflow. 几乎可以肯定是堆栈溢出。 You are allocating, what, 3 ^ 10 * 9 * sizeof(int) bytes! 你正在分配什么,3 ^ 10 * 9 * sizeof(int)字节! Use int *a = (int*)malloc(N * sizeof(int)) instead, where N is the number of ints you want. 请改用int *a = (int*)malloc(N * sizeof(int)) ,其中N是您想要的整数。 Then you can simulate an N-dimensional array on it. 然后你可以模拟它上面的N维数组。

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] . 我将解释如何在一维数组上模拟二维数组。假设它有一行宽度为10.然后你通过a[10 * 2 + 5]访问第三行的第五个值。 In general, you do a[width * (row - 1) + column] . 通常,您执行a[width * (row - 1) + column]

Second method. 第二种方法。 You can allocate an array of pointers to pointers of ints: 您可以分配指向int的指针数组:

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. ......将其扩展到更多维度,作为读者的练习。

The size of your array is 3^10 * 8 * sizeof(int). 数组的大小为3 ^ 10 * 8 * sizeof(int)。 Assuming a 32 bit int, sizeof(int) is four bytes and the size of your array is: 假设一个32位的int,sizeof(int)是四个字节,并且数组的大小是:

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

So you're stack isn't that big and you're overflowing the stack. 所以你的堆栈并不是那么大而且你的堆栈溢出来了。

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 我猜你的堆栈限制为2Mbytes

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM