C - pointer is not null after freeing it

2019-03-07 03:27发布

Does the value of pointer become NULL after freeing it?

int* p = malloc(sizeof(*p));

free(p);

if(p==NULL)
    printf("Null\n");
else
    printf("Not null\n");

Output:

 Not null

Well, I assume not;

Anyway, I have asked a question earlier today :

Check it out here: C - How can I free dynamically allocated memory?

List* head1 = NULL;

insertFront(&head1, 1);
insertFront(&head1, 2);

print(head1);

while (head1)
{

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

if(head1 == NULL)
    printf("Null\n");
else
    printf("Not null\n");

Output in this case:

Null

In this case after freeing head1 (nodes also) the head1 becomes null, does'nt it?

And finally, am I missing some concepts?

head1 is null, however p isn't.

My Question is:

Why values differs between head1 and p?

5条回答
聊天终结者
2楼-- · 2019-03-07 03:47

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.

查看更多
趁早两清
3楼-- · 2019-03-07 03:48

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?

查看更多
趁早两清
4楼-- · 2019-03-07 03:53

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.

查看更多
Fickle 薄情
5楼-- · 2019-03-07 04:03

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.

查看更多
爷、活的狠高调
6楼-- · 2019-03-07 04:04

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.

查看更多
登录 后发表回答