尽管我在C中释放,但肯定失去了记忆

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

我想创建一个函数,当给定一个结构体中包含指向另一个相同类型的结构体的指针时,它会找到所有指针并释放它们。
结构将是:

typedef struct example_ {
    uint16_t something;
    bool blabla;
    struct example_ *further_in; 
} example;

我创建的用于释放每个指针的函数是:

bool free_examples(example p) {
    bool isCounting = true;
    int16_t count = 0;
    example firstexample = p;
    while (isCounting) // counts how many examples there are
    {
        if (p.further_in == NULL)
        {
            isCounting = false; 
        }
        else if (p.further_in != NULL)
        {
            count++;
            p = *(p.further_in);
        }       
    }
    p = firstexample;
    example *n = malloc(sizeof(example));
    for (int i = 0; i < count; i++) // frees every pointer?
    {
        n = p.further_in;
        free(p.further_in);
        p = *(n);
    }
    free(n);    
    return true;
}

首先,我是编程和 C 新手,所以我什至不知道我的代码是否达到了我想要的效果。
其次,我的问题是,当我通过 valgrind 运行此命令时,它返回该行肯定丢失了 16 个字节:

example *n = malloc(sizeof(example));

如你所见,稍后我释放了“n”。我不明白怎么还是泄露了。

预先感谢您的帮助!

c memory-leaks free
1个回答
0
投票

这段代码

p = firstexample;
example *n = malloc(sizeof(example));
for (int i = 0; i < count; i++) // frees every pointer?
{
    n = p.further_in;
    free(p.further_in);
    p = *(n);
}
free(n); 

至少会产生内存泄漏,而且具有未定义的行为。

在这一行

example *n = malloc(sizeof(example));

已分配内存,其地址已分配给指针

n
。然后在下面的 for 循环中,指针
n
被重新分配

    n = p.further_in;

所以分配的mempry的地址就丢失了。

还有这个说法

p = *(n);

访问已释放的内存,导致未定义的行为。

© www.soinside.com 2019 - 2024. All rights reserved.