I want to create a function that, when given a struct with a pointer in it to another struct of the same type, it finds all of the pointers and frees them.
The struct would be:

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;
}

First of all, I'm new to programming and C so I don't even know if my code does what I want it to do.
Secondly, my problem is that when I run this through valgrind, it returns that 16 bytes are definitely lost at this line:

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

如您所见,稍后我会释放"n".我不明白它怎么还在泄露.

提前感谢您的帮助!

推荐答案

此代码片段如下:

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;

因此,分配的内存的地址会丢失.

也是这句话

p = *(n);

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

此外,还不清楚传递的类型为example:

bool free_examples(example p) {
                          ^^^

是否存储在动态分配的内存中.如果它确实被放在动态分配的内存中,那么它也应该被释放,并且函数的声明至少应该是这样的:

void free_examples(example *p) {
                           ^^^

返回类型bool也没有意义.

请注意,与释放分配的内存的过程相比,计算非空指针的数量没有意义,而且效率低下,而且是多余的.

如果您有一个单链接列表,其中列表的所有 node 都是动态分配的,则该函数可能如下所示:

void free_examples( example **p ) 
{
    while ( *p != NULL )
    {
        example *current = *p;
        *p = ( *p )->further_in;
        free( current );
    }
}

如果在调用方中有一个指向动态分配的列表第一个 node 的指针,例如:

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

然后调用该函数,如下所示:

free_examples( &head );

C++相关问答推荐

是否可以在C中进行D3 D12申请?

设计处理各种数据类型的方法和数据 struct

为什么已经设置的值在C中被重置为for循环条件中的新值?

为什么在C中设置文件的位置并写入文件,填充空字符?

__VA_OPT__(,)是否可以检测后面没有任何内容的尾随逗号?

测量ARM MCU中断延迟的问题

为什么删除CAP_DAC_OVERRIDE后创建文件失败?

如何在CANbus RX/TX FIFO起始地址寄存器(ATSAME 51)的特定地址初始化数组?

如何在GET_STRING输入后对少数几个特定字符串进行C判断?

如何在GDB中查看MUSL的源代码

C堆栈(使用动态数组)realloc内存泄漏问题

用于计算位数和的递归C函数

生成的头文件不包括用户定义的文件

如何解释数组中的*(ptr)和*(ptr+2)?

计算时出现奇怪的计算错误;N Select K;在C中

如何在Rust中处理C的longjmp情况?

System V 消息队列由于某种原因定期重置

为什么写入关闭管道会返回成功

cs50拼写器分配中的无限循环

C23 中的 [[reproducible]] 和 [[unsequenced]] 属性是什么?什么时候应该使用它们?