Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
835 views
in Technique[技术] by (71.8m points)

c - Segmentation fault when allocating large arrays on the stack

When I compiled this simple C code it's fine but after uncommenting the line it shows segmentation fault. I don't know what's wrong with this. Please help.

#include<stdio.h>
int main()
    {
    int arr[10002][10002];
    int color[10002];
    int neigh;
 // scanf("%d",&neigh);
    return 0;
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're blowing the stack with arr and color. Presumably when your call to scanf is commented out the compiler optimises all these variables away, but when it's present it attempts to allocate memory on the stack.

Make the variables global, and read up on stack memory vs heap memory.

#include<stdio.h>

int arr[10002][10002];
int color[10002];

int main()
{
    int neigh;
    scanf("%d",&neigh);
    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...