我的程序出现内存泄漏,我不明白为什么。我得到了一个4大小的链表数组,并且valgrind说存在内存泄漏。

这是我的结构:

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


这是我在create函数中的分配:

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;

最佳答案

您的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
}

关于c - 释放列表数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39074290/

10-12 14:47