Heap corruption - debug assertion failed. in dbghe

2019-07-30 17:47发布

At runtime I get debug assertion failed.

in dbgheap.c line 1322 expression _crtIsValidHeapPointer(pUserData)

If I run in a debugger I get a breakpoint triggered in line shown below.

How can I fix this allocation/de-allocation error?

I have 2 functions in a header file:

struct union_find_t;

struct union_find_t* union_find_init(int n);

void union_find_free(struct union_find_t* uf);

and in the .c file the implementation for these 2 functions is:

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
}

1条回答
神经病院院长
2楼-- · 2019-07-30 17:58

This:

typedef struct union_find_t

is a typedef for:

*union_find_t;

So when you do this:

malloc(sizeof(union_find_t));

you just allocate space for a pointer to that struct, not for a struct as you need to!

Try with:

malloc(sizeof(struct union_find_t));

instead.

查看更多
登录 后发表回答