Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation fault: 11 with large array [duplicate]

Tags:

c

A simple program compiles fine but gives run-time error: segmentation fault: 11

int length=10000;
int num=100;
int num1=20;
int datablocklen=400002; //datablocklen=2*num1*length+2

int main(){
  double arr[num*length];
  double res[num][num];
  for(int i=0;i<num;i++){
    for(int j=0;j<num;j++){
      res[i][j]=0;
    }
  }
  for(int i=0;i<(num*length);i++){
    arr[i]=i;
  }
  int ntile=(int)(num/num1);
  double array_task[datablocklen];
  for(int i=0;i<ntile;i++){
    for(int j=0;j<ntile;j++){
    array_task[datablocklen-2]=i*num1*length;
    array_task[datablocklen-1]=j*num1*length;
      for(int k=0;k<(num1*length);k++){
        array_task[k]=arr[i*num1*length+k];
        array_task[num1*length+k]=arr[j*num1*length];
      }
    }
  }
return 0;
}

gcc -o test -std=c99 test.c to get the executable.

Strange still, the error does not show up if length is assigned a small value, say, 1000. But when it is larger than 10000, segmentation fault occurs.

Please note that I always keep an eye on the the value of datablocklen to make sure that datablocklen=2*num1*length+2. So if length or num1 changes, I will also change variable datablocklen.

I still have some problem dealing with gdb under mac, OS yosemite. So I have not debugged the program with gdb. But if I comment the inner for loop, the loop indexed by k, the program executes fine. I mean, no error message.

like image 534
dudu Avatar asked Apr 14 '26 11:04

dudu


1 Answers

I think here stack memory is the issue here.

Two solutions:

  1. Either increase the stack size for your process. Normally ulimit -s will show default size for any process in linux, mac

  2. Instead of such large array allocation in stack double arr[num*length];use malloc for such memory allocation in heap.

like image 174
Jeegar Patel Avatar answered Apr 16 '26 04:04

Jeegar Patel