C - pointer is not null after freeing it

余生颓废 提交于 2019-12-02 13:32:55

The condition of the loop

while (head1)
       ^^^^^^
{

    List *temp = head1;
    head1 = head1->next;
    free(temp);
}

becomes equal to false when the data member next of the next node is equal to NULL

head1 = head1->next;
^^^^^         ^^^^^

This has nothing common with the function free. The function accepts the argument by value. That is it deals with a copy of the original [pointer. So the original pointer itself will not be changed.

Freeing a pointer doesn't change its value.

You need to manually set it to NULL after freeing it if that's the behaviour you want.

When you free a pointer, you're not changing its value. You're just returning whatever memory it points to back to the pool.

In fact, given that free takes the value of a pointer instead of its address, that alone is enough to tell you that the value isn't changed, since there's no way to change it.

The reason head1 is NULL at the end of the loop is because you are modifying the value of head1 inside the loop to go down the list until it reaches the end. We know we're at the end of the list when we find a NULL value in the next pointer. So at the end of the loop, head1 is NULL.

When you allocate memory, the pointer naturally points to the beginning of the allocated block for you to reference. However, when you free a pointer, only the memory itself is freed.

The catch is that the pointer is still pointing to that location in memory that it was previously set to, even though the value of that block of memory is no longer useful.

Setting to NULL is not an automatic operation after freeing.

dtell

As mentioned above freeing a pointer has nothing to do with changing its value. It just tells the memory management that the related block (on the heap) can be reused.

This SO question provides further information: What is the difference between freeing the pointer and assigning it to NULL?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!