C-释放指针后,该指针不为null [英] C - pointer is not null after freeing it

查看:205
本文介绍了C-释放指针后,该指针不为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

释放指针后,指针的值是否为NULL?

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");

输出:

 Not null

好吧,我认为不是;

无论如何,我今天早些时候问了一个问题:

Anyway, I have asked a question earlier today :

在此处查看: C-如何释放动态分配的内存?

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");

在这种情况下的输出:

Null

在这种情况下,在释放head1(也有节点)之后,head1变为null,不是吗?

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

最后,我是否缺少一些概念?

And finally, am I missing some concepts?

head1为空,但p不是.

head1 is null, however p isn't.

我的问题是:

为什么head1和p之间的值不同?

推荐答案

循环条件

while (head1)
       ^^^^^^
{

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

当下一个节点的数据成员next等于NULL时,

等于false

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

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

这与功能free没有共同之处.该函数按值接受参数.那就是它处理原始[指针的副本.因此原始指针本身不会被更改.

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.

这篇关于C-释放指针后,该指针不为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆