调整堆大小时C中出现realloc错误

dgtucam1  于 2023-03-17  发布在  其他
关注(0)|答案(1)|浏览(261)

我想在C语言中使用realloc作为heap的插入函数,代码如下:

typedef struct MaxHeap {
    int size;
    int* heap;
} MaxHeap;

void max_insert(MaxHeap* max_heap, int* key_index, int key) { // O(logn)
    max_heap->heap = realloc((max_heap->size+1), sizeof * max_heap->heap);
    max_heap[max_heap->size] = N_INF;
    max_heap->size += 1;
    increase_key(max_heap, key_index, max_heap->size, key)
}

我得到了这样的警告:
warning: passing argument 1 of ‘realloc’ makes pointer from integer without a cast [-Wint-conversion],我尝试了此修复:

max_heap->heap = realloc((max_heap->heap), (max_heap->size+1) * sizeof(*(max_heap->heap)));

更新

我是这么做的

void max_insert(MaxHeap* max_heap, int* key_index, int key) { // O(logn)
    int* temp = realloc (max_heap->heap, (max_heap->size + 1) * sizeof (*(max_heap->heap)));
    if (!temp) exit(1);
    max_heap->heap = temp;
    max_heap->heap[max_heap->size] = N_INF;
    max_heap->size += 1;
    increase_key(max_heap, key_index, max_heap->size, key);
    temp = 0;
}

我得到了这个错误realloc(): invalid old size

uujelgoq

uujelgoq1#

您已经将参数交换为realloc()

(max_heap->size+1)

计算结果为int,但realloc()的第一个参数需要void *指针。请将其替换为:

(max_heap->heap);

realloc()的调用变为:

realloc (max_heap->heap, (max_heap->size + 1) * sizeof (*(max_heap->heap)));

请注意,此操作失败的原因有两个:
1.内存不足,realloc()返回NULL,这将不会被注意到,因为我们没有检查realloc()的返回值。随后的操作现在将写入NULL/解除引用NULL/从NULL阅读NULL,这将调用未定义的行为。
1.如果realloc()返回NULL,我们将无法访问原始内存,这将导致内存泄漏。

修复:

使用临时指针保存realloc()的返回值:

int *tmp = realloc (... , ...);

if (!tmp) {
    perror ("realloc()");
    /* realloc() was unable to allocate memory.
     * The original memory is left untouched.
     * Handle error here.
     */
} 
/* Now we can assign the result to `max_heap->heap`: */
max_heap->heap = tmp;
tmp = 0;      /* This is unnecessary, but eliminates a dangling pointer. */

相关问题