重复reallocs后的段故障

Segfault after repeated reallocs

本文关键字:故障 段故障 reallocs 重复      更新时间:2023-10-16

编辑:非常感谢你的回答。这是对的,我将尝试使用向量代替。

我有一个动态分配内存的程序。

这个类有一个属性,它是一个结构数组(**)和一个指针数组(*),指向结构数组的每个元素,所以我做了2个malloc。这个结构体叫做context。

realloc工作正常,不返回NULL,但只要我有超过2个元素,程序会给我一个段错误,当试图保存数组元素中的值。如何防止这种分段故障?

int my_class::method(uint32_t struct_element)
{
    int i= this->numofcontexts;
    if(this->local_context_array == NULL)
        // That means it is empty and we have to make our first malloc
    {
        this->local_context_array = (context_t**) malloc(sizeof(context_t*));
        *(this->local_context_array) = (context_t*) malloc(sizeof(context_t));
        i++;
        std::cout << "n1 Malloc was made of size " << sizeof(context_t)<<"n";
    }
    else
        // Array is not empty and we have to use realloc
    {
        this->local_context_array = (context_t**) realloc(this->local_context_array, (i+1)*sizeof(context_t*));
        *(this->local_context_array) = (context_t*) realloc(*(this->local_context_array), (i+1)*(sizeof(context_t)));
        std::cout << "n1 Realloc was made of size " << (i+1)*(sizeof(context_t)) <<"n";
        i++;
        std::cout << "nWe now have " << i <<" elementsn";
        // As soon as the array is bigger than 2 elements, this gives segmentation fault:
        //(this->local_context_array[i-1])->struct_element = struct_element;
     }

从发布的代码和您描述的症状来看,您似乎没有在最后执行此操作:

this->numofcontexts = i;

如果这是真的,那么每次你调用这个方法,它会发现nummofcontexts == 0和local_context_array不是NULL,所以它会移动到你的else子句,当它将数组重新分配到i+1(总是1)。

第一次调用将成功,第二次调用也将成功,数组大小为1个元素,如果您尝试在此时分配元素超过[0],您可能会得到一个段错误。在[1]处可能没有出现段错误的原因通常与占用空间并被丢弃的其他变量有关,但这些变量并不总是立即产生段错误。