调整堆大小时 C 中的 realloc 错误

问题描述 投票:0回答:1

我想在 C 中的堆插入函数中使用 realloc。这是代码:

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

c heap
1个回答
6
投票

您已将参数交换为

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
    ,这将调用未定义的行为。
  2. 如果
    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. */
© www.soinside.com 2019 - 2024. All rights reserved.