2017-11-25 899 views
1

在運行時我得到調試斷言失敗。堆損壞 - 調試斷言失敗。在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 
} 
+0

你可以嘗試運行沒有'free(uf-> parent)的程序嗎? free(uf-> rank);'並檢查錯誤是否再次出現.. –

+1

'union_find_t;'是一個指針的typedef,所以'malloc(sizeof(union_find_t));'只是爲指針分配空間,並且不適用於結構。看起來你應該從typedef中移除'*'。 –

+0

@BoPersson - 實際上你的解決方案可能會更好。儘管typedef struct union_find_t int * parent; int * rank; int組件; } union_find_t;看起來有點奇怪 –

回答

1

此:

typedef struct union_find_t 

是一個typedef用於:

*union_find_t; 

所以,當你這樣做:

malloc(sizeof(union_find_t)); 

你只是分配空間指針到結構,而不是因爲你需要一個結構!

嘗試用:

malloc(sizeof(struct union_find_t)); 

代替。

+1

這是棘手和微妙的 - 謝謝! –