Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }
like image 425
schrodinger Avatar asked Jul 10 '11 11:07

schrodinger


2 Answers

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;
}
like image 53
ta.speot.is Avatar answered Sep 30 '22 11:09

ta.speot.is


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.

like image 31
Scott C Wilson Avatar answered Sep 30 '22 13:09

Scott C Wilson