[英]Free a structure… I'm not sure if I do it right
我的程序管理結構的鏈表。
這是我的結構:
typedef struct wagon wagon;
typedef struct wagon{
wagon *next;
marchandise_ptr *liste;
double volume_courant;
}train_ptr;
其中wagon * next是指向鏈接列表的下一個“單元格”的指針,而marchandise_ptr * list是指向另一個鏈接列表的指針。 要釋放結構,請按照以下步驟操作:
在int main()中:
train_ptr *train=creer_un_train(...)//so train is the beginning of my linked list
liberer_train(&train);
我的職能是:
創建一個“貨車”
wagon *creer_wagon(marchandise_ptr *liste,double volume_courant){ //it creates a wagon
assert(volume_courant>=0);
wagon *wag=malloc(sizeof(wagon));
if(wag==NULL)
return NULL;
wag->next=NULL;
wag->volume_courant=volume_courant;
wag->liste=liste;
return wag;
}
在鏈表的末尾添加創建的“旅行車”:
train_ptr *ajouter_wagon_a_la_fin_du_train(train_ptr *train,double volume_courant, marchandise_ptr *liste){
wagon *wag=creer_wagon(liste,volume_courant);
if(wag==NULL)
return NULL;
if(train==NULL)
train=wag;
else{
train_ptr *wag_current=train;
while(wag_current->next!=NULL)
wag_current=wag_current->next;
wag_current->next=wag;
}
return train;
}
創建火車:
train_ptr *creer_un_train(unsigned int nombre_de_wagons,marchandise_ptr *liste){
assert(nombre_de_wagons>=0);
int i;
train_ptr *train=NULL;
for(i=0;i<nombre_de_wagons;i++){
train=ajouter_wagon_a_la_fin_du_train(train,rand()%10,liste);
if(train==NULL)
return NULL;
}
return train;
}
免費搭乘火車:
void liberer_train(train_ptr **train){
train_ptr *p_current = *train;
while(p_current!=NULL){
*train = p_current->next;
p_current->next=NULL;
free(p_current->liste);
free(p_current);
p_current = *train;
}
}
PS:liste是指向鏈接列表的beginnig的指針:
typedef struct marchandise marchandise;
typedef struct marchandise{
double volume;
double volume_total;
char nom;
marchandise *suivant;
}marchandise_ptr;
感謝您的關注! (對不起我的英語,我不是母語人士。...:D)
從你的creer_wagon
功能,它似乎並不像liste
應該由釋放liberer_train
功能,因為它沒有被分配creer_wagon
功能。
下面這個邏輯,在那里你做調用函數creer_wagon
應負責的liste
成員,因為你將有一個有效的指針給它的調用函數的范圍,你的風險的雙重free
的的liste
成員。
如果每train
只需要liste
一個liste
,而無需修改它,則可以這樣定義結構
typedef struct wagon{
wagon *next;
const marchandise_ptr *liste;
double volume_courant;
}train_ptr;
這樣可以防止意外地嘗試修改或free
liste
成員。
這種設計在許多火車可以指向同一個liste
,盡管它增加了struct wagon
用戶的責任,因為他們應該注意liste
成員的內存管理。 如果是這種情況,我會雙重推薦const
限定詞。
在我看來,這是一個合理的方式來考慮是否由您分配了liste
。
我建議您像這樣修復liberer_train
函數
void liberer_train(train_ptr **train) {
train_ptr *p_current = *train;
train_ptr *suivant = NULL;
while (p_current != NULL) {
suivant = p_current->next;
free(p_current);
p_current = suivant;
}
/* make the pointer NULL, so it's not a dangling pointer in the caller function anymore. */
*train = NULL;
}
而且,我建議你改變
typedef struct wagon train_ptr;
至
typedef struct wagon *train_ptr;
要么
typedef struct wagon train;
例如,由於后綴_ptr
使train_ptr x;
內容產生了train_ptr x;
x
是一個指針,但不是。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.