Segmentation fault when allocating large arrays on the stack

后端 未结 2 1441
旧巷少年郎
旧巷少年郎 2020-12-07 02:17

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.



        
相关标签:
2条回答
  • 2020-12-07 03:09

    Variables allocated inside a function are put on the stack, which has a limited size. You can allocate them on the (larger) heap instead by using malloc.

    0 讨论(0)
  • 2020-12-07 03:14

    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;
    }
    
    0 讨论(0)
提交回复
热议问题