一.野指针初始化
如果知道指针指向的明确指向哪里,就直接赋值,如果不知道,可以直接赋值NULL。
#include<stdio.h>
int main()
{
int a = 10;
int* pa = &a;
int* p = NULL;
return 0;
}
反例(错误原因:空指针是不能直接使用):
int*p=NULL;
*p=20//err
二.小心指针访问越界。
三.当指针不在使用时,及时置NULL。使用之前及时检查它的有效性。
检查起有效性时可以用到assert(断言)或者if语句。
if语句:
#include<stdio.h>
int main()
{
int arr[10] = { 0,1,2,3,4,5,6,7,8,9 };
int* p = &arr[0];//此时将数组首元素的地址已经赋给p了;
for (int i = 0; i < 10; i++)
{
*(p++) = i;//此时p已经越界
}
int* p = NULL;
p = &arr[0];
if(*p!=NULL)
{
}
}
assert(使用时注意事项: 要包含assert.h头文件。格式为:assert(p!=NULL);)
#include<stdio.h>
#include<assert.h>
int main()
{
int a = 10;
int* p = &a;
assert(p != NULL);
* p = 10;
printf("%d", *p);
return 0;
}
四.避免返回局部变量的地址。
例如:
#include<stdio.h>
int* test()
{
int n = 20;
return &n;
}
int main()
{
int* p = test();
printf("%d", *p);//此时p成了野指针。
return 0;
}