by jcranmer · 5y ago · 0 comments
void remove_entry(node_t *entry) {
// curr_ref is the address of the link pointing to curr
node_t **curr_ref = &head;
node_t *curr = *curr_ref;
while (curr != NULL && curr != entry) {
// Advance curr_ref and curr
curr_ref = &curr->next;
curr = *curr_ref;
}
if (curr) { *curr_ref = curr->next; }
}
Choosing names somewhat more rationally, and making it clear that "curr" always points to the current node, and that "curr_ref" is the address of whatever pointer we followed to arrive at curr, makes it easier to establish the invariant that updating curr_ref is sufficient to insert or remove curr into a list, no matter if it's referring to the head link of a list or the next link of the prior node.Now, on a different note, I am a bit puzzled because I don’t see a free(*ptr) call in Linus’ or anyone else’s code. The code, as-is, would cause a memory leak.
There’s a need to capture the curr_ref before it’s overwritten, and free it after it’s overwritten.
So generally, list implementations in C will not free the node, only remove references to it and return it.