一个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\n");
    else
        printf("BBBBBBB\n");
    return 0;
}

编译执行,输出:

BBBBBBB

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

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

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

编译运行输出:

AAAAAA

 
posted @ 2015-07-16 14:16  Magnum Programm Life  阅读(183)  评论(0编辑  收藏  举报