我想在堆的插入函数中使用 C 中的 realloc。这是代码:
\ntypedef 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}\nRun Code Online (Sandbox Code Playgroud)\n我收到这个警告:
\nwarning: passing argument 1 of \xe2\x80\x98realloc\xe2\x80\x99 makes pointer from integer without a cast [-Wint-conversion]我尝试了这个修复:
max_heap->heap = realloc((max_heap->heap), (max_heap->size+1) * sizeof(*(max_heap->heap)));\n\nRun Code Online (Sandbox Code Playgroud)\n更新
\n我这样做了:
\nvoid 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}\nRun Code Online (Sandbox Code Playgroud)\n我收到了这个错误realloc(): invalid old size
您已将参数交换为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)
请注意,此操作失败的原因有两个:
realloc()返回了NULL,这将不会被注意到,因为我们没有检查 的返回值realloc()。后续操作现在将写入/取消引用/读取NULL,这将调用未定义的行为。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)