一个free的问题

请看下面的代码:

#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>


void destroy(int * p){
    if(p != NULL)
    {
        free(p);
        p = NULL;
    }
}
int main()
{
    int *p;
    p = (int*)malloc(sizeof(int)*5);
    p[0] = 1;
    p[1] = 2;
    destroy(&p);
    if(p == NULL)
        printf("AAAAAAAA
");
    else
        printf("BBBBBBB
");
    return 0;
}

编译执行,输出:

BBBBBBB

函数里面的p是传入p的临时变量,指向的空间的确free成功,但是赋值NULL却是赋值给临时变量.

修改destroy函数如下,解决这个问题.

void destroy(int ** p){
    if(*p != NULL)
    {
        free(*p);
        *p = NULL;
    }
}

编译运行输出:

AAAAAA

 
原文地址:https://www.cnblogs.com/biglucky/p/4651196.html