1/21 If I have a linked list of structs and many of those structs have
members that are structs then what is the best way to free() the
memory when I am done with them? I thought I would walk the list
and do a free() on each member of each struct, but that generates
errors like free(): invalid pointer, presumably because I don't
always allocate memory in each struct. No, I never took a class in
memory management (obviously). In a Java World I don't worry
about all this! ;)
\_ Why don't you just check the pointer before calling free? i.e.
if (p) { free(p); }
\_ This was my first inclination and it doesn't change anything.
\_ This should have no effect in this case. The if only checks if
p is null, and if p is null, most versions of free will ignore
p is NULL, and if p is NULL, most versions of free will ignore
it anyway.
\_ All versions. It's a requirement in the standard.
\_ Hah, you assume all libc implementations are
compliant. Well, okay, things are better these days.
That said, if you aren't allocating the memory for the pointer,
you NEED to set the pointer to NULL. Preferably at the point
that the enclosing struct is allocated. Otherwise that pointer
may just be nonsense, which the if won't catch.
\_ Well, do the structs contain other structs, or pointers to other
structs? If struct A contains struct B, struct B is allocated
and free'd as part of struct A.
If struct A contains a pointer to struct B, you need to make sure
you're allowed to free the pointer before you do, perhaps there
are multiple pointers to B, and B shouldn't be free'd until all
the pointers are done.
If you are supposed to free pointer to B, but you think you might
be accidentally freeing it twice, you're going to have to be more
careful and figure out where exactly you should free it. There's
no easy way out of that.
\_ You need to define the difference between and owning an object and
referring to one. It's a logical difference -- the owners are
responsible for lifetime, referring pointers just are assigned.
\_ You're not doing something like the following, right???
while (p != NULL) {
free(p);
p = p->next;
} |