简体   繁体   English

在C中对大型数组使用realloc的分段错误

[英]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. 数组的大小由len表示,数组中剩余的空间由reserved表示。 If I append 5650 points it works fine, but as soon as I go 5700 or more it gives me a segmentation fault. 如果我附加5650点,则效果很好,但一旦达到5700或更高,它就会给我带来细分错误。 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. realloc返回一个指向新内存的指针。 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. realloc将调整数组的大小(如果可以),然后将返回指向数据新地址的指针。 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. 另外需要注意的是非常重要realloc可以存储移动到不同的位置,如果它需要。 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. 因此,如果realloc将数据移动到其他地方,而您不应该将其写入其他地方,这是未定义的行为,这可能会导致您看到的段错误。 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. 机会是,直到5650点没有决定是由做realloc ,但更重要的是量引发了移动到不同的指针。

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. 解决方法是使用realloc返回的指针,并确保在执行任何操作之前先检查该指针是否为null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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