当delete一个指针后,指针值 就变为无效了。虽然指针已经无效,但在很多机器上仍然保存着(已经释放了的)动态内存的地址。在delete之后,指针就变成了人们所说的空悬指针,即指向一块曾经保存数据对象但现在已经无效的内存的指针。
野指针即未初始化指针,在指针即将要离开其作用域之前释放掉它所关联的内存可以避免空悬指针问题。在指针关联的内存被释放掉以后,就没有机会继续使用指针了。
空悬指针
1.
{
char *dp = NULL;
/* ... */
{
char c;
dp = &c;
}
/* c falls out of scope */
/* dp is now a dangling pointer */
}2.
#include <stdlib.h>
void func()
{
char *dp = malloc(A_CONST);
/* ... */
free(dp); /* dp now becomes a dangling pointer */
dp = NULL; /* dp is no longer dangling */
/* ... */
}3.
int *func(void)
{
int num = 1234;
/* ... */
return #
}野指针
int f(int i)
{
char *dp; /* dp is a wild pointer */
static char *scp; /* scp is not a wild pointer:
* static variables are initialized to 0
* at start and retain their values from
* the last call afterwards.
* Using this feature may be considered bad
* style if not commented */
}

被折叠的 条评论
为什么被折叠?



