c - segmentation fault while freeing memory integer array -


so problem within function while i'm trying free memory array q.

int makegrid (float *x, float *y, float squaresize, float map, int npoints) {    int score=0, i;    int m = map/squaresize;   int nsqr = m*m;   int *q;   q = null;   q = (int *) malloc (sizeof(int)*nsqr);        for(i=0;i<nsqr;i++)     q[i] = 0;      int helper1 = 0;   int helper2;   float helperf;    for(i = 0; < npoints; i++)   {      helperf = x[i] - e;      helper1 = floor(helperf/squaresize)*(m);        helperf = y[i] - e;      helper2 = floor(helperf/squaresize);       helper1 += helper2;      q[helper1]++;    }    for(i=0;i<nsqr;i++)   {       if(q[i] >= 1 && q[i] <= 4)         score--;      else if (q[i] == 0)         score++;      else         score+=5;   }    free(q);   q = null;    return score;  } 

the function's goal create score generated grid, map size of whole grid, while squaresize size of each square in grid, npoints size of both x , y vectors, , function called loop changes squaresize.

i don't know what's wrong free though , appreciate suggestions (the size of x , y arrays supposed above 5k)

free can fail when you've messed memory elsewhere. doesn't segfault before since memory yours, you've screwed memory management data structures, free accesses outside memory.

it's guaranteed line:

 q[helper1]++; 

put assertion (or print) before if helper1 > nsqr

 printf("too big!  %d > %d\n", helper1, nsqr);  q[helper1]++; 

..or based on comments, check negative numbers, too.


Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -