5

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;
    }
Timothy Jones
  • 21,495
  • 6
  • 60
  • 90
schrodinger
  • 247
  • 1
  • 2
  • 7
  • 12
    It looks like you probably have... *drum roll* ...a **Stack Overflow** ! *rimshot* – Paul R Jul 10 '11 at 11:07
  • which number are you typing in? – dynamic Jul 10 '11 at 11:08
  • I think is a problem, allocating memory for many elements for the array int arr. And you have reached the limit. Obviously it depends also from the OS you are using. Read this link : http://bytes.com/topic/c/answers/131385-maximum-size-array – Alberto Solano Jul 10 '11 at 11:13

2 Answers2

12

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;
}
ta.speot.is
  • 26,914
  • 8
  • 68
  • 96
5

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.

ta.speot.is
  • 26,914
  • 8
  • 68
  • 96
Scott C Wilson
  • 19,102
  • 10
  • 61
  • 83