经过反复的reallocs后,Segfault

时间:2014-08-11 07:41:09

标签: c++

编辑:非常感谢您的回答。没错,我会尝试使用向量。

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

该类有一个属性,它是一个结构数组(**),也是一个指针数组(*),它指向结构数组的每个元素,因此我创建了2个Mallocs。该结构被称为" 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 <<" elements\n";
        // As soon as the array is bigger than 2 elements, this gives segmentation fault:
        //(this->local_context_array[i-1])->struct_element = struct_element;

     }

1 个答案:

答案 0 :(得分:0)

从发布的代码和您描述的症状来看,最后您似乎没有这样做:

this->numofcontexts = i;

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

第一次调用将成功,第二次调用也将成功,数组大小为1,如果此时尝试分配给[0]以上的元素,则可能会出现段错误。您可能无法在[1]处获得段错误的原因通常与占用空间并被删除的其他变量相关,但并不总是立即生成段错误。