简体   繁体   中英

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

I have a function which appends a point in 3D space to the end of an array and then it calculates the time that it takes to append each point. But when I ran my code, it created an initialized the code fine. But when it tried to run the function append, it just seg faulted right away. I've been looking at my code but I can't figure out why it seg faulted. Can anybody help me out?

This is my 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 to take care of a 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 into array
    pa->len++;
    return 0;
}

These are the two structs I use:

typedef struct point
{
  double x, y, z; // location in 3D space
} point_t;


typedef struct 
{
  size_t len; // number of points in the array
  point_t* points; // an array of len point_t structs 
  size_t reserved;  
} point_array_t;

Probably you might have a bug in the if condition:

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

What you probably want is:

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

which translates to:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM