不是NULL指针,是指向“垃圾”内存的指针。“野指针”是很危险的。
“野指针”的成因主要有两种:
1)指针变量没有被初始化。
2)指针p被free之后,没有置为NULL,让人误以为p是个合法的指针。
3) 指针操作超越了变量的作用范围。这种情况让人防不胜防。
#include <stdio.h>
#include <stdlib.h> //表示引用了malloc 函数
#include <string.h>
#define N 20
typedef struct student{
int no;
char name[N];
float score;
}Stu;
Stu * get_info()
{
Stu * p;
if((p = (Stu *)malloc(sizeof(Stu))) == NULL)
{
printf("malloc failed\n");
return 0;
}
p->no = 1;
strcpy(p->name,"Tom");
p->score = 90;
return p;
}
int main(int argc, const char *argv[])
{
Stu * s;
if((s = get_info()) ==NULL)
{
return 0;
}
printf("Student info:%d %s %.2f\n",s->no,s->name,s->score);
free(s);
s = NULL;
return 0;
}