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".我不明白它怎么还在泄露.
提前感谢您的帮助!