C - 在指针指针上使用realloc会导致分段错误

时间:2017-08-15 14:32:35

标签: c pointers memory realloc

我正在尝试使用realloc,因为我想提高代码的速度。当满足某个条件时,我想将void double指针重新分配给更大的大小,但是我得到了一个分段错误。这是代码。

if (p_bheap->currentSize == p_bheap->arraySize){
    p_bheap->arraySize = p_bheap->arraySize*2 + 1;
    p_bheap->pp_array = realloc(p_bheap->pp_array, p_bheap->arraySize);
}

然而,这会导致分段错误。但是,如果我自己重新分配功能,那就可以了。

if (p_bheap->currentSize == p_bheap->arraySize){
    p_bheap->pp_array = bheap_reallocate(p_bheap);
}

void** bheap_reallocate(bheap* p_bheap){
    p_bheap->arraySize = p_bheap->arraySize*2 + 1;
    void** pp_newArray = malloc(p_bheap->arraySize*sizeof(void*));
    for (int i = 0; i < p_bheap->currentSize; i++){
        pp_newArray[i] = p_bheap->pp_array[i];
    }
    free(p_bheap->pp_array);
    return pp_newArray;
}

是否有任何明显的错误可以被发现,我没有看到?对于那些想知道我正在编写二进制堆的人。

2 个答案:

答案 0 :(得分:0)

如果您有一个先前分配的对象,比如str并想要将其内存调整为另一个大小,请使用临时变量来防止在realloc失败时内存丢失。插图:

char *str = calloc(20, 1);
if(str) // should always check return of calls to [c][m][re]alloc.
{ // at this point, str owns 20 bytes of memory.  If you use str in a subsequent
  // call to realloc, and the call fails, then the memory previously allocated in 
  // the original call to calloc() will be lost.  (memory leak).
....
char *tmp = {0};//So instead, use a temporary variable to accept memory
                //and provide a way to recover if allocation fails

tmp = realloc(str, 40);//newsize (40) in bytes
if(!tmp) //test reallocation
{
    //reallocation failed.
    //free previously allocated memory, and decide how to proceed.
    //In this case, return a NULL, and let the calling function decide.
    free(str);//if allocation fails, free the previous object and leave
    return NULL;
}
//reallocation succeeded.  Proceed normally
str = tmp;//reallocation succeeded, assign its address to str and proceed normally

答案 1 :(得分:-1)

您无法使用相同的内存空间来接收结果。尝试使用临时数组或分配另一个空格。

相关问题