c - Getting a seg fault when trying to append a point in 3D space to the end of an array -


i have function appends point in 3d space end of array , calculates time takes append each point. when ran code, created initialized code fine. when tried run function append, seg faulted right away. i've been looking @ code can't figure out why seg faulted. can me out?

this append code:

int point_array_append( point_array_t* pa, point_t* p) {     assert( pa );     assert( p );      if( pa->len < pa->reserved )     {         size_t new_res = pa->len * 2 + 1;  // add 1 take care of null array         size_t sz= new_res * sizeof(point_t);         point_t* tmp = realloc( pa->points, sz );         if( tmp == 0 )             return 1; //fail         pa->points = tmp;         pa->reserved = new_res;     }     pa->points[pa->len] = *p; // copy struct array     pa->len++;     return 0; } 

these 2 structs use:

typedef struct point {   double x, y, z; // location in 3d space } point_t;   typedef struct  {   size_t len; // number of points in array   point_t* points; // array of len point_t structs    size_t reserved;   } point_array_t; 

probably might have bug in if condition:

if( pa->len < pa->reserved ) 

what want is:

if ( <there no more free slots in array> )     reallocate 

which translates to:

if (pa->len >= pa->reserved)     ... reallocation 

Comments

Popular posts from this blog

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -