【发布时间】:2018-05-09 07:14:42
【问题描述】:
在运行时我得到调试断言失败。
in dbgheap.c line 1322 expression _crtIsValidHeapPointer(pUserData)
如果我在调试器中运行,我会在如下所示的行中触发断点。
如何解决此分配/取消分配错误?
我在一个头文件中有两个函数:
struct union_find_t;
struct union_find_t* union_find_init(int n);
void union_find_free(struct union_find_t* uf);
在 .c 文件中,这两个函数的实现是:
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
}
【问题讨论】:
-
你可以尝试在没有
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* 排名;整数组件; } union_find_t;看起来有点奇怪
-
这是一个品味问题。如果你在任何地方都写
struct union_find_t,你甚至不需要typedef。通常的原因是避免在名称前输入struct。 -
从 typedef 中删除
*一切正常,但是,从结构的角度来看,您将struct命名空间与typedef命名空间以及具有相同名称的事物混合在一起在两者中不必引用相同的类型。
标签: c pointers memory-management malloc heap-memory