码迷,mamicode.com
首页 > 其他好文 > 详细

野指针产生的原因

时间:2017-03-30 21:44:19      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:概念   char   style   null   不同   nbsp   string   malloc   stdio.h   

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//野指针产生的原因
//指针变量和它所指向的内存空间变量是两个不同的概念
//释放了指针所指的内存空间 但是指针变量本身没有重置成null

//造成释放的时候 通过if(p1 != NULL)

//避免方法:1)定义指针的时候 初始化成null 2)释放指针所指向的内存空间后,把指针重置成null
int main(void)
{

char *p1 = NULL;
p1 = (char *)malloc(100);
if(p1 == NULL)
{
return ;
}
strcpy(p1, "11112222");

printf("p1:%s \n", p1);


if(p1 != NULL)
{
free(p1);
p1 = NULL;    //释放了指针所指的内存空间 但是指针变量本身没有重置成null
}
if(p1 != NULL)
{
free(p1);

}
return 0;
}

野指针产生的原因

标签:概念   char   style   null   不同   nbsp   string   malloc   stdio.h   

原文地址:http://www.cnblogs.com/Liu-Jing/p/6648428.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!