Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

minor improvement in freeing nodes in linked list in C

Look at this code that wants to free all the malloced nodes inside a linked list in C:

    ptr = list;
    while (ptr != NULL)
    {
        node *next = ptr->next;
        free(ptr);
        ptr = next;
    }

The reasoning is that, we need a temporary variable next to store the pointer to the next node before freeing the current node.

Do you see that node *next = ptr->next; is inside the loop? So that every time the loop runs, there is a new temporary node created to store the pointer to the next node. Is it better if we create the variable node outside the loop and inside the loop we just reassign it?

Like this:

    ptr = list;
    node *next = NULL;
    while (ptr != NULL)
    {
        next = ptr->next;
        free(ptr);
        ptr = next;
    }

Would it be more efficient?

like image 390
Linh Chi Nguyen Avatar asked Sep 16 '25 12:09

Linh Chi Nguyen


1 Answers

there is a new temporary node created to store the pointer to the next node

No, there's a new temporary node pointer created.

Both versions will likely be optimized into exactly the same assembler code which can be seen in this demo where clang produces two identical functions and gcc too.

like image 126
Ted Lyngmo Avatar answered Sep 19 '25 03:09

Ted Lyngmo