【发布时间】:2019-03-28 13:41:11
【问题描述】:
我的 C 代码出现了非常不寻常的行为。我正在实现一个最小和最大堆,如果堆容量达到,它应该动态改变大小。问题是当我调用realloc 来增加堆的元素数组时,它以以下方式运行(假设两个堆都处于最大容量):
如果我只在其中一个堆中添加一个新元素,那么重新分配就可以完美地工作。
如果我在两个堆中添加一个新元素(一个接一个),第二个会完美地重新分配,但第一个的数据会因一些垃圾值和一些零而损坏。
请看下面的相关功能。 (问题发生在 main 函数的第 8 行和第 9 行)。
我不明白为什么在不同的堆上调用insert 函数会改变前一个堆的值。
我不知道是 realloc 功能搞砸了还是我的打印功能搞砸了。感谢您的帮助。
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define leftChild(x) (x << 1)
#define rightChild(x) ((x << 1) + 1)
#define parent(x) (x >> 1)
typedef int T;
typedef struct {
int size;
int capacity;
T *elements;
} Heap;
void swap(Heap *heap, int a, int b) {
T temp = heap->elements[a];
heap->elements[a] = heap->elements[b];
heap->elements[b] = temp;
}
Heap *newHeap(int capacity) {
Heap *heap = malloc(sizeof(Heap));
heap->capacity = capacity;
heap->size = 0;
heap->elements = malloc(sizeof(T) * (capacity + 1));
return heap;
}
void increaseKey(Heap *heap, int i, T key) {
heap->elements[i] = key;
while (i > 1 && heap->elements[parent(i)] < heap->elements[i]) {
swap(heap, parent(i), i);
i = parent(i);
}
}
void decreaseKey(Heap *heap, int i, T key) {
heap->elements[i] = key;
while (i > 1 && heap->elements[parent(i)] > heap->elements[i]) {
swap(heap, parent(i), i);
i = parent(i);
}
}
void insert(Heap *heap, T key, bool isMinHeap) {
if (heap->size >= heap->capacity) {
heap->elements = realloc(heap->elements, heap->capacity * 2);
heap->capacity = heap->capacity * 2;
}
heap->size++;
heap->elements[heap->size] = 0;
if (isMinHeap) decreaseKey(heap, heap->size, key);
else increaseKey(heap, heap->size, key);
}
void printHeap(Heap *heap) {
int i;
printf("[");
for (i = 1; i < heap->size; i++) {
printf("%d,", heap->elements[i]);
}
if (heap->size != 0) {
printf("%d", heap->elements[heap->size]);
}
printf("]\n");
}
int main(void) {
Heap *minHeap = newHeap(5);
Heap *maxHeap = newHeap(5);
for (int i = 0; i < 5; i++) {
insert(minHeap, i, true);
insert(maxHeap, i, false);
}
printf("now start\n");
insert(minHeap, 10, true);
insert(maxHeap, 10, false);
printHeap(minHeap);
printHeap(maxHeap);
}
【问题讨论】:
-
parent(i)中的decreaseKey()是什么? -
什么是
swap()和parent()?您发布了这么多代码,再多 3 行添加#includes 不会有什么不同。 -
我不知道是 realloc 功能出了问题还是我的打印功能出了问题。 你的操作系统是什么?视窗? Linux?您可能使用的
realloc()的副本有多少亿(如果不是数十亿)正被整个地球使用?在您发现如此广泛使用的函数实现中的错误之前,宇宙的热寂更有可能发生,该函数的使用量与realloc()一样多。 -
您经常访问
heap->elements[heap->size],这是超出范围的。 (是的,我知道您为一个插槽分配了内存只是为了确定,但感觉(并且可能是)错误的。)哦,您需要在 realloc 中使用sizeof(T),就像使用malloc一样。 -
@mch 抱歉,我以为我包括了所有内容。请在最近的编辑中找到最新的代码。
标签: c pointers data-structures realloc