如何释放链接结构的结构

问题描述 投票:1回答:2

我有这个结构

struct room {
    char* name;               
    char* description;         
    struct room *north;       
    struct room *south;       
    struct room *east;       
    struct room *west;          
    struct container* items;   
};

所以我应该写一个函数struct room* destroy_room(struct room* room);释放所有用于创建房间的内存,并返回NULL作为新的房间引用。所以我认为只是做

free(room);
return NULL;

可以解决问题,但是没有。

c linked-list structure
2个回答
2
投票

我将使用两个单独的函数来解决。第一个是destroy_room,它将释放一个房间,并从其邻居中删除对其自身的引用:

struct room* destroy_room(struct room* room) {
    if (!room) return;
    if (room->name) free(room->name);
    if (room->description) free(room->description);
    if (room->items) free_items(room->items);

    // remove the references to this room from its neighbors
    if (room->north) room->north->south = NULL;
    if (room->south) room->south->north = NULL;
    if (room->east) room->east->west = NULL;
    if (room->west) room->west->east = NULL;

    free(room);

    return NULL;
}

然后,该函数可用于编写递归函数,以释放给定房间可到达的所有房间。该函数保存对邻居的引用,然后释放给定的空间,然后递归释放邻居:

struct room* destroy_rooms_rec(struct room* room)
{
    if (!room) return;

    // save references to neighbors
    struct room* north = room->north;
    struct room* south = room->south;
    struct room* east = room->east;
    struct room* west = room->west;

    // free this room
    destroy_room(room);

    // free all neighbors
    destroy_rooms_rec(north);
    destroy_rooms_rec(south);
    destroy_rooms_rec(east);
    destroy_rooms_rec(west);

    return NULL;
}

注意:我假设存在像free_items(struct container* items)这样的函数,可以释放items是什么。


2
投票

正如Jabberwocky所说,“没有任何东西会自动释放”,因此您的函数可能看起来像:

void destroy_room(struct room* room)
{
    if (!room) return;
    if (room->name) free(room->name);
    if (room->description) free(room->description);
    if (room!=room->north) destroy_room(room->north);
    if (room!=room->south) destroy_room(room->south);
    if (room!=room->east) destroy_room(room->east);
    if (room!=room->west) destroy_room(room->west);
    free_items(room->items);
    free(room);
}
© www.soinside.com 2019 - 2024. All rights reserved.