1. 野指针通常是因为指针变量中保存的值不是一个合法的内存地址而造成的。
2. 野指针不是NULL指针,是指向不可用内存的指针。
3. NULL指针不容易用错,因为一个if语句可以很好的判断一个指针是不是NULL。
注:C语言中没有任何手段可以判断一个指针是否是野指针。
野指针的由来:
1)局部指针变量没有初始化
#include <stdio.h>
#include <string.h>
struct Student
{
char* name;
int number;
};
int main()
{
struct Student s;
strcpy(s.name, "my name"); // OOPS!
s.number = 10;
system("pause");
return 0;
}
2)使用已经释放过的指针
#include <stdio.h>
#include <malloc.h>
#include <string.h>
void func(char* p)
{
printf("%s\n", p);
free(p);
}
int main()
{
char* s = (char*)malloc(20);
strcpy(s, "Hello World");
func(s);
printf("%s\n", s); // OOPS!
return 0;
}
3)指针所指向的变量在指针之前被销毁
#include <stdio.h>
char* func()
{
char p[] = "my name";
return p;
}
int main()
{
char* s = func();
printf("%s\n", s); // OOPS!
return 0;
}
避免使用一个已释放的指针的最好做法是:当不再用一个指针时,free掉之后立即赋值为NULL。
int *p=(int *)malloc(5*sizeof(int));
//....
free(p);
p=NULL;
//.......
//.......
if(p!=NULL)
{
for(int i=0;i<5;i++)
{
p[i]=i;
}
}
system("pause");
4. 用malloc申请了内存之后,应该立即检查指针值是否为NULL,防止使用值为NULL的指针。
int *p=(int *)malloc(10*sizeof(int));
if(p!=NULL)
{
//do something here
}
free(p);
5. 柔性数组的使用
typedef struct soft_array
{
int len;
int array[];
}SoftArray;
printf("%d\n",sizeof(SoftArray)); //输出4
注:上面语句中,并未给array[]分配空间。但是这样可以避免数组越界,根据需要分配空间。
SoftArray *sa=(SoftArray *)malloc(sizeof(SoftArray)+10 * sizeof(int));
sa->len=10;
for(int i=0;i<sa->len;i++)
{
sa->array[i]=i+1;
}