Segmentation fault

From Liki

Jump to: navigation, search

Sometimes you might get a Segmentation Fault when running a compiled c++ or c program.

If your arrays are small, it might be that you tried to go beyond the array length, i.e.:

int j[100]

for(i=0; i<=101; i++){j[i]=i;}

Sometimes it is just because your arrays are too big for the usual way of declaration.

In that case, use pointers and malloc: i.e replace

double Au[nn];
double ADU[nn];
double Aphi[nn];

with

int nn=100000;
double *Au;
double *ADU;
double *Aphi;
Au = (double *) malloc(nn * sizeof(double));
ADU = (double *) malloc(nn * sizeof(double));
Aphi = (double *) malloc(nn * sizeof(double));
...
PROGRAM DETAILS...Treat arrays as usual for now on, for example:
...
Au[i]=u; SUMu+=u; ADU[i]=DU; Aphi[i]=phi; SUMDU+=DU;
...
BUT BE CLEAN!  FREE THE MEMORY WHEN DONE:
...
free(Au);
free(ADU);
free(Aphi);

Alternatively (thanks to Ben Coy and Ernest Mamikonyan):

  #include <stdio.h>
  #include .....
 
  #define LINES 200002

  // global in case it's too large
  double data[LINES][5];

  main(){
  .....
  }
Personal tools