Home > database >  Why need an extra variable to free memory?
Why need an extra variable to free memory?

Time:05-01

In C, define nodes as:

typedef struct node {
    int data;
    struct nod *next;
} NodeT;

To free memory:

void freeLL (NodeT *list) {
    NodeT *p, *temp;
    p = list;
    while (p != NULL) {
        temp = p->next;
        free (p);
        p = temp;
    }
}

Why do we need the extra variable temp?

CodePudding user response:

If you will rewrite the while loop without the auxiliary variable like that

 while (p != NULL) {
 free(p);
 p = p->next;
 }

then this statement'

 p = p->next;

will invoke undefined behavior because there is an access to already freed memory.

So you need a variable to preserve the address of the next node

temp = p->next;

before freeing the memory with the node containing the data member next.

CodePudding user response:

For example, "a->b->c->d" is a linked table. a is the first node.

After you free the memory of node "a"(use variable "p" pointing to a), you have to get the address of b to continue to free the left nodes. If there is no "temp", at this time you just have the address of node "a", and memory of node "a" has been freed. If you want to use p->next to obtain the address of "b", you can't confirm the p->next is the address you want, because the memory here is not protected after you free and may be used by other program and be changed. So it means you lost the address of left node.

So you have to use "temp" to save the address of next node before you free one node, and you need the address of current node to free(). It means you need two address, two variable.

CodePudding user response:

If you do not want to use tmp you can use recursion :

void freeLL(NodeT *list) {
    if (list == NULL) {
        return;
    } else {
        freeLL(list->next;
    }
    free(list);
}

That free the end of list before the begin. If you free the memory a pointer point at, you may not use this memory : trying to access this memory result in undefined behaviour (it may work but more certainly crash at some point). In real life : if you have a box (A) with a box (B) inside, if you empty box (A) in a trash , then you can not empty box (B) because you have no more access to it, and it’s contents is no more accessible but wasted.

  • Related