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

v_h*_*ead 0 c heap

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

\n
typedef struct MaxHeap {\n    int size;\n    int* heap;\n} MaxHeap;\n\nvoid max_insert(MaxHeap* max_heap, int* key_index, int key) { // O(logn)\n    max_heap->heap = realloc((max_heap->size+1), sizeof * max_heap->heap);\n    max_heap[max_heap->size] = N_INF;\n    max_heap->size += 1;\n    increase_key(max_heap, key_index, max_heap->size, key)\n}\n
Run Code Online (Sandbox Code Playgroud)\n

我收到这个警告:

\n

warning: passing argument 1 of \xe2\x80\x98realloc\xe2\x80\x99 makes pointer from integer without a cast [-Wint-conversion]我尝试了这个修复:

\n
max_heap->heap = realloc((max_heap->heap), (max_heap->size+1) * sizeof(*(max_heap->heap)));\n\n
Run Code Online (Sandbox Code Playgroud)\n

更新

\n

我这样做了:

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

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

\n

Har*_*ith 6

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

(max_heap->size+1)
Run Code Online (Sandbox Code Playgroud)

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

(max_heap->heap);
Run Code Online (Sandbox Code Playgroud)

调用变为realloc()

realloc (max_heap->heap, (max_heap->size + 1) * sizeof (*(max_heap->heap)));
Run Code Online (Sandbox Code Playgroud)

请注意,此操作失败的原因有两个:

  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. */
Run Code Online (Sandbox Code Playgroud)