2017-08-15 108 views
-1

我想使用realloc,因为我想提高代码中的速度。当某个条件满足时,我想将一个无效双指针重新分配给一个更大的大小,但是我得到了一个分段错误。这是代码。C - 在指针上使用realloc指针导致分段错误

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; 
} 

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

+5

传递到大小['realloc'](http://en.cppreference.com/w/c/memory/realloc)就像传递到['malloc']的大小(HTTP ://en.cppreference.com/w/c/memory/malloc):***字节中的大小***(不是元素)。 –

+4

顺便说一句,不要将['realloc'](http://en.cppreference.com/w/c/memory/realloc)的结果指定回作为参数传递的指针。如果['realloc'](http://en.cppreference.com/w/c/memory/realloc)失败,它将返回'NULL',你将失去原始的指针并且有内存泄漏。 –

+0

我没有完全理解你的解决方案。我必须改变什么? –

回答

-1

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

+0

没有阵列。只是指针。 –

+2

这是* a *问题,但它不是OP所具有的*问题。 –

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