链接列表malloc内存泄漏

时间:2014-01-23 20:40:11

标签: c malloc free

我有以下结构

typedef struct Body
{
    struct Body *next;
    struct Body *prev;
    SDL_Rect value;
} Body;

我想用以下

分配身体的新部分
void init_body(Body **out_body, SDL_Rect *rect, Body *prev)
{
     struct Body* new_body = malloc(sizeof(struct Body));
     new_body->next = NULL;
     new_body->prev = prev;
     new_body->value = *rect;
     *out_body = new_body;
}

然而(我在窗户上)记忆博士正在提出以下抱怨:

Error #1: LEAK 24 direct bytes 0x02901b08-0x02901b20 + 0 indirect  bytes  
# 0 replace_malloc                [d:\drmemory_package\common\alloc_replace.c:2292]  
# 1 init_body                     [E:/Development/Projects/RipTide/main.c:61]  
# 2 create                        [E:/Development/Projects/RipTide/main.c:75]  
# 3 SDL_main                      [E:/Development/Projects/RipTide/main.c:213]  
# 4 console_main                  [../src/main/windows/SDL_windows_main.c:140]  
# 5 WinMain@16                    [../src/main/windows/SDL_windows_main.c:177]  
# 6 main                          [E:/Development/Projects/RipTide/main.c:263]  

我如何清理此内存泄漏?

创造的逻辑

void create(SDL_Renderer *renderer, Snake *snake) {
    SDL_Rect r = SDL_CreateRect(10, 10, 100, 100);

    snake->size = 1;
    snake_init_body(&snake->body, &r, NULL);
    snake->surf = SDL_CreateRGBSurface(0, 10, 10, 32, 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF);
    SDL_FillRect(snake->surf, NULL, 0xAAAAAAFF);
    snake->texture = SDL_CreateTextureFromSurface(renderer, snake->surf);
}

DOH最后需要释放(我从未这样做过):

void snake_free(Snake *snake)
{
    struct Body *abody = snake->body;

    while (abody != NULL)
    {
        if (abody->next == NULL)
        {
            free(abody);
            break;
        }
        else
        {
            abody = abody->next;
        }

        if (abody != NULL)
            free(abody->prev);
    }
}

1 个答案:

答案 0 :(得分:2)

您是否正在经历某个时刻并释放列表中的每个节点?