Segmentation fault in C

末鹿安然 提交于 2021-01-27 12:50:26

问题


I need to fill 2-d array with 0s. But compiled program falls with this error. What's wrong?

int main()
{
    int vert[1001][1001];
    int hor[1001][1001];
    int dudiag[1416][1416];
    int uddiag[1416][1416];
    int n, k, m;
    int row, col;
    int i, j;
    int answer = 0;

    for(i = 0; i <= 1000; i++){
        for(j = 0; j <= 1000; j++){
            vert[i][j] = 0;
            hor[i][j] = 0;
        }
    }
...
}

When cycle is commented out, it works properly.


回答1:


The problem is that you are trying to allocate too much memory in the automatic store (AKA "on the stack"). When you comment out the cycle, the compiler optimizes out the allocation along with the now-unused variables, so you do not get a crash.

You need to change the allocation to either static or dynamic memory (AKA "the heap") to fix this problem. Since the issue is inside main, making the arrays static would be an appropriate choice.

int main()
{
    static int vert[1001][1001];
    static int hor[1001][1001];
    static int dudiag[1416][1416];
    static int uddiag[1416][1416];
    ...
}

In functions other than main you could make these arrays dynamic, allocate them using malloc/calloc, and then free them once your program has finished using them.




回答2:


What's wrong?

You are trying to reserve on stack several 4MB arrays. On many Linux distributions, the default stack size is 8MB (you can change this with ulimit -s unlimited).

Even with unlimited stack, the Linux kernel will not extend stack by more than some constant, so ulimit -s unlimited may not help avoiding the crash.

As dasblinkenlight's answer says, if you need arrays that large, allocate them dynamically.

Finally, an explicit for loop is an inefficient way to zero out an array. Using memset is likely to be much more efficient, and requires much less code.



来源:https://stackoverflow.com/questions/23184955/segmentation-fault-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!