列表节点未被释放,仍然消失

时间:2014-12-02 19:42:31

标签: c linked-list

我的ls版本的另一个意想不到的行为。

上下文:我为每个打开的目录生成一个输出列表,然后添加一个节点来显示接下来要显示的目录,与原始ls一样。

要处理-a选项,我只需删除所有以"."开头的节点,如果没有为我的ls提供-a选项。为了避免删除显示目录路径名的节点,我检查节点内容不是以"./"开头,也不是".:"

以下是代码:

t_list          *ft_rem_hidden(t_list **output)
{
    t_list          *cursor;
    t_list          *tmp;

    cursor = *output;
    while (cursor)
    {
            tmp = cursor->next;
            if (ft_strnequ((char const *)cursor->content, ".:", 2) == 0
                    && ft_strnequ((char const *)cursor->content, ".", 1)
                    && ft_strnequ((char const *)cursor->content, "./", 2) == 0)
                            ft_lstfreeone(output, cursor);
            cursor = tmp;
    }
    return (*output);
}

现在有趣的部分。我在循环之前检查了(整个)列表,第一个节点的内容按预期".:" 我检查了所说的节点没有通过if,并且正如预期的那样,它没有。 我在while循环后检查了列表,aaaa和".:"不再存在。

以下是ft_lstfreeone的代码,虽然我已经使用了一段时间没有问题,但我看不到任何其他罪魁祸首。好吧,除了我的无知。

void        ft_lstfreeone(t_list **alst, t_list *to_free)
{
    t_list      *cursor;
    t_list      *tmp;

    if (alst && *alst && to_free)
    {
        cursor = *alst;
        if (cursor == to_free)
        {
            *alst = cursor->next;
            ft_memdel((void **)&cursor->content);
            ft_memdel((void **)cursor);
        }
        else
        {
            while (cursor && cursor->next && cursor->next != to_free)
                cursor = cursor->next;
            if (cursor->next == to_free)
            {
                tmp = cursor->next;
                cursor->next = cursor->next->next;
                ft_memdel((void **)&cursor->content);
                ft_memdel((void **)tmp);
            }
        }
    }
}

我的节点在哪里?这几乎就是让我不再拥有功能性的ls,这真是令人生气。任何提示欢迎。

编辑:更多测试显示它只是关注的。:节点。如果我要求我的ls显示任何其他目录的内容,其名称在第一行显示就好了。

编辑2:我创建了一个包含整个事物来源的git仓库,以防有人想仔细看看。 https://github.com/pdecrat/ft_ls

2 个答案:

答案 0 :(得分:1)

您的代码存在多个问题 - 您实际上并未删除节点本身,因为您没有将指针的地址传递给节点。

"。:"正在删除是因为在ft_lstfreeone中您需要ft_memdel tmp->content而不是cursor->content

根据编码,您可能会删除"。:"删除之后的节点时。

当你把&在tmp / cursor前面调用ft_memdel。

答案 1 :(得分:0)

在@TonyLee评论中,cursor可能指向一个已释放的节点,使cursor跟随一个废话。为什么不在主代码中的cursor->next语句之前保存if,并在cursor之后将if设置为它,这样无论节点是否都可以安全地进行循环获得自由,并避免冒险?