利用二级指针释放一级指针
正确案例
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void P_Free(char **myp)
{
if(myp == NULL)
{
return ;
}
free(*myp);
*myp = NULL;
}
int main()
{
char *p = NULL;
p = (char *)malloc(100);
strcpy(p, "1234");
P_Free(&p);
}
错误案例
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void P_Free(char *myp)
{
if(myp == NULL)
{
return ;
}
free(myp);//到这里其实没什么问题,可以释放内存
myp = NULL;//但是到这里就有问题了,因为我们要避免野指针,
//所以要让指针指向NULL;但是实参没办法改变形参,
//所以主函数中的p的指向还是指向原来的位置,变成了野指针
//但是我们可以在主函数中这个函数之后加入p = NULL;但是这样
//违背了建立这个函数的初心
}
int main()
{
char *p = NULL;
p = (char *)malloc(100);
strcpy(p, "1234");
P_Free(p);
}