释放一系列列表

时间:2016-08-22 08:09:51

标签: c arrays

我的程序中有内存泄漏,我无法理解原因。我有一个4大小的链表列表,valgrind说有内存泄漏。

这是我的结构:

struct node {
    achievementMen100m player;
    char* playerName;
    Men100mAchievement playerAchiInRound;
    char*currentRound;
    struct node *head;
    struct node *next;
} node, *Node;

这是我在create function中的分配:

for(int i=0; i<4;i++){
    OG->games->head->phases[i] = malloc(sizeof(struct node)); //VALGRIND SAYS MEMORY ALLOCATED HERE NOT FREED!//
    OG->games->head->phases[i]->head=NULL;
    OG->games->head->phases[i]->next=NULL;
    OG->games->head->phases[i]->playerAchiInRound = 0;
}

这是我的free-list功能:

void listDestroy(struct node * list) {
struct node * currentPlayer = list;
struct node * temp;
while (currentPlayer != NULL) {
    temp = currentPlayer;
    currentPlayer=currentPlayer->next;
    free(temp->playerName);
    free(temp);
}
list = NULL;
free(list);

}

这是ADT的自由功能:

void olympicGamesDestroy(OlympicGames OG) {
if (OG == NULL) {
    return;
}
if (OG->games == NULL) {
    free(OG);
    return;
}
if (OG->games->head == NULL) {
    free(OG->games);
    free(OG);
    return;
}
for (int i=0; i<4;i++) {
    listDestroy(OG->games->head->phases[i]->head);
}
free(OG->games->next);
free(OG->games->head);
free(OG->games);
free(OG);
}

更新 这是我的整个.h文件

typedef struct men100 {
Men100mAchievement olympicMinimum;
Men100mAchievement olympicSkipPre;
char* roundNames[4];
struct node* phases[4];
} men100, *Men100;

typedef struct gameList {
int name;
men100* head;
struct gameList *next;
} gameList, *GameList;


typedef struct olympicGames {
GameList games;
int numOfGames;
} olympicGames, *OlympicGames;

1 个答案:

答案 0 :(得分:0)

你的void olympicGamesDestroy(OlympicGames OG)看起来很奇怪!

您正在OG->games->head->phases[i]分配。

那么,你在哪里free?您只能使用OG->games->head->phases[i]->head而非OG->games->head->phases[i]

显示实际的OlympicGames数据结构。

<强>更新

我没有太多时间来验证整个代码:

但您可以尝试以下方法:

for(int i=0; i<4; i++)
{
    listDestroy(OG->games->head->phases[i]->head);
    free(OG->games->head->phases[i]); // you need this
}