为什么我的指针释放后不为空? [英] Why is my pointer not null after free?

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

问题描述

void getFree(void *ptr)
{
    if(ptr != NULL)
    {
        free(ptr);
        ptr = NULL;
    }
    return;
}
int main()
{
char *a;
a=malloc(10);
getFree(a);
if(a==NULL)
    printf("it is null");
else
    printf("not null");
}

为什么这个程序的输出不为空?

推荐答案

由于指针被复制的通过值的给你的函数。您正在分配 NULL 来变量的本地副本( PTR )。这不把它分配给了原件。

Because the pointer is copied by value to your function. You are assigning NULL to the local copy of the variable (ptr). This does not assign it to the original copy.

内存仍然会被释放,所以你可以不再安全存取它,但你原来的指针不会 NULL

The memory will still be freed, so you can no longer safely access it, but your original pointer will not be NULL.

这同样的,如果你是传递一个 INT 来一个函数。你不会想到原来的 INT 通过该功能进行编辑,除非你是传递一个指针。

This the same as if you were passing an int to a function instead. You wouldn't expect the original int to be edited by that function, unless you were passing a pointer to it.

void setInt(int someValue)
{
    someValue = 5;
}

int main()
{
    int someOtherValue = 7;
    setInt(someOtherValue);
    printf("%i\n", someOtherValue); // You'd expect this to print 7, not 5...
    return 0;
}

如果你想为null原来的指针,你必须通过一个指针到指针:

If you want to null the original pointer, you'll have to pass a pointer-to-pointer:

void getFree(void **ptr)
{
    /* Note we are dereferencing the outer pointer,
    so we're directly editing the original pointer */

    if(*ptr != NULL)
    {
        free(*ptr);
        *ptr = NULL;
    }

    return;
}

int main()
{
    char *a;
    a=malloc(10);

    getFree(&a); /* Pass a pointer-to-pointer */

    if(a==NULL)
        printf("it is null");
    else
        printf("not null");

    return 0;
}

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

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