我正在嘗試在 C 中創建一個簡單的家譜程式,但是我遇到了一個問題,即以下結構的實體拒絕空閑并且我遇到了記憶體泄漏
typedef struct Person {
struct person* *parents[2];
struct person* partner;
struct person* *children[32];
} person;
包含它的隨附結構是
typedef struct Tree {
person* top;
person* current;
} tree;
Tree 結構釋放得很好,但是當我嘗試釋放 person 結構的 malloced 記憶體時,我得到了記憶體泄漏,我很確定這表明記憶體。
void newPerson(tree *t){
person *p = malloc(sizeof(person));
...
這是記憶體分配的功能
...
if (t->current){
t->top = p;
t->current = p;
...
在同一個函式中,兩個指標都設定為指向 p。
int main(){
tree *t = malloc(sizeof(tree));
t->current = NULL;
newPerson(t);
free(t->current);
free(t);
return 0;
}
這是 main 函式中創建樹變數并釋放它的代碼。從我嘗試解決此問題的各種方法中,發生了以下情況。
- 如果我將 free(p) 放在創建 Person 的同一個函式中,一切正常,沒有錯誤也沒有記憶體泄漏
- 如果我嘗試釋放 t->current,我會收到一個泄漏消毒器錯誤,告訴我直接泄漏 Person 被分配的確切位置
- 如果我嘗試釋放 t->top,我會收到一個關于未知地址錯誤的 SEGV。
現在我知道問題出在 t 的某個地方,但我對問題的真正含義只有最微弱的線索,要么我對 malloc 和 free 的了解已經退化到我做錯了什么并且我看不到它的地步,或其他事情正在發生。
編輯:代表
#include <stdio.h>
#include <stdlib.h>
typedef struct Branch {
struct branch* otherbranch;
} branch;
typedef struct Tree {
branch* root;
branch* current;
} tree
void newBranch(tree *t){
branch *b = malloc(sizeof(branch));
b->otherbranch = NULL;
if (t->current){
t->root = b;
t->current = b;
}
//free(b); //case 1 where freeing works
}
int main(){
tree *t = malloc(sizeof(tree));
t->current = NULL;
newBranch(t);
free(t->root); //case 3 where segv occurs
//free(t->current); //case 2 where memory leak occurs
free(t);
return 0;
}
uj5u.com熱心網友回復:
當您輸入此代碼時
void newBranch(tree *t){
branch *b = malloc(sizeof(branch));
b->otherbranch = NULL;
if (t->current){
t->root = p;
t->current = p;
}
//free(b); //case 1 where freeing works
}
t->current 為 null,因此您永遠不會設定 t->root 或 t->current。
然后回傳 main 并執行free(t->root)
,此時 t->root 無效。您可能希望將 t->root 初始化為 NULL,也可能將 t->current 初始化
我也假設你的意思t->root = b
不是= p
,因為沒有 pi 可以看到
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/431189.html
上一篇:如何從C中的陣列中洗掉一個元素?