简体   繁体   中英

Segmentation fault using realloc on large arrays in C

I am trying to implement a dynamic array - if the array is full and you add another point it will double the size of the array. The size of the array is denoted by len and the space left in the array is denoted by reserved. If I append 5650 points it works fine, but as soon as I go 5700 or more it gives me a segmentation fault. Any ideas as to what could be causing this?

int point_array_append( point_array_t* pa, point_t* p )
{
    if(pa->reserved==0)
    {
        if(!(realloc(pa->points, sizeof(point_t)*(pa->len * 2))))
            return 1;
        pa->reserved=pa->len;
    }
    pa->len++;
    pa->reserved--;
    pa->points[(pa->len)-1] = *p;
    return 0;
}

realloc returns a pointer to the new memory. You can't just throw that away like that.

realloc will resize the array (if it can) and then it will return the pointer to the new address of your data. If it fails it will return a null pointer, you should check for that (which you did, which is good to see!). Additionally it is important to note that realloc can move the memory to a different location if it needs to. In this code if such a move were to happen you would be in trouble because you only keep track of where the original pointer to the data is. So if realloc moved the data somewhere else you'd be writing to somewhere you shouldn't be which is undefined behavior and this could cause the segfault you are seeing. Chances are that up until 5650 points no move was done by realloc but more than that amount triggered a move to a different pointer.

The fix is to use the pointer returned by realloc and make sure that you check that this pointer is not null before you do anything with it.

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