和野指针相关的编码习惯

    xiaoxiao2021-12-14  18

    见如下程序实例: [cpp]  view plain  copy  print ? #include <stdio.h>   #include <stdlib.h>      int main()   {       char *p1 = NULL;       printf("p1:%d, &p1:%d\n",p1,&p1);          p1 = (char*)malloc(100);    //为p1在堆区分配空间       if(p1 == NULL)              //若为空直接return出程序       {           return;       }       printf("p1:%d, &p1:%d\n",p1,&p1);          if(p1 != NULL)              //目的:释放p1       {           free(p1);           //只释放了p1指向的堆区空间  并没有将指针p1置为空       }       printf("p1:%d, &p1:%d\n",p1,&p1);             system("pause");       return 0;   }  

    程序运行结果为:

    [cpp]  view plain  copy  print ? p1:0, &p1:2031188   p1:2233584, &p1:2031188   p1:2233584, &p1:2031188   请按任意键继续. . .  

    由结果看出,p1并不为0,也就是在释放p1时,仅仅释放的是p1指向的内存空间,并没有将指针p1指为空,此时p1就成了野指针!

    避免策略--养成一个习惯:

    1、在定义一个指针时初始化为NULL

    2、释放指针指向的内存空间时,将指针重置为NULL

    即修改后上述实例代码为:

    [cpp]  view plain  copy  print ? #include <stdio.h>   #include <stdlib.h>      int main()   {       char *p1 = NULL;       printf("p1:%d, &p1:%d\n",p1,&p1);          p1 = (char*)malloc(100);    //为p1在堆区分配空间       if(p1 == NULL)              //若为空直接return出程序       {           return;       }       printf("p1:%d, &p1:%d\n",p1,&p1);          if(p1 != NULL)              //目的:释放p1       {           free(p1);           //只释放了p1指向的堆区空间  并没有将指针p1置为空           p1 = NULL;          //--------------------------------------------重新置为空       }       printf("p1:%d, &p1:%d\n",p1,&p1);             system("pause");       return 0;   }  

    转载请注明原文地址: https://ju.6miu.com/read-965269.html

    最新回复(0)