堆损坏 - 调试断言失败。在dbgheap.c行1322表达式_crtIsValidHeapPointer(pUserData)
问题描述:
在运行时我得到调试断言失败。堆损坏 - 调试断言失败。在dbgheap.c行1322表达式_crtIsValidHeapPointer(pUserData)
in dbgheap.c line 1322 expression _crtIsValidHeapPointer(pUserData)
如果我在一个调试器中运行,我会得到如下所示的一行触发的断点。
我该如何解决这个分配/解除分配错误?
我有在头文件2层的功能:
struct union_find_t;
struct union_find_t* union_find_init(int n);
void union_find_free(struct union_find_t* uf);
和.c文件执行对这些2个功能是:
typedef struct union_find_t {
int* parent;
int* rank;
int components;
} *union_find_t;
struct union_find_t* union_find_init(int n) {
struct union_find_t* uf = malloc(sizeof(union_find_t));
uf->parent = malloc(n * sizeof(int));
uf->rank = malloc(n * sizeof(int));
uf->components = n;
for (int i = 0; i < n; ++i) {
uf->parent[i] = i;
uf->rank[i] = 0;
}
return uf;
}
void union_find_free(struct union_find_t* uf) {
free(uf->parent);
free(uf->rank);
free(uf); //*** breakpoint triggered here
}
答
此:
typedef struct union_find_t
是一个typedef用于:
*union_find_t;
所以,当你这样做:
malloc(sizeof(union_find_t));
你只是分配空间指针到结构,而不是因为你需要一个结构!
尝试用:
malloc(sizeof(struct union_find_t));
代替。
+1
这是棘手和微妙的 - 谢谢! –
你可以尝试运行没有'free(uf-> parent)的程序吗? free(uf-> rank);'并检查错误是否再次出现.. –
'union_find_t;'是一个指针的typedef,所以'malloc(sizeof(union_find_t));'只是为指针分配空间,并且不适用于结构。看起来你应该从typedef中移除'*'。 –
@BoPersson - 实际上你的解决方案可能会更好。尽管typedef struct union_find_t int * parent; int * rank; int组件; } union_find_t;看起来有点奇怪 –