NULL指针 Void* 和野指针

在C和C++的语言中常常有这几个概念:

NULL指针、空指针、Void *指针、野指针(Wild Pointer)甚至垂悬指针(Dangling Pointer)。

1.NULL指针,一般用于指向一个预留的值,不一定是0,通常是没有真正意义上的实体。被称作空指针。所以任何对象或者函数的地址都不可能是空指针。

常用于

初始化一个指针 如 int *ptr = NULL;

或者判断内存分配是否失败,if(NULL == ptr) ……

或者一个指针被delete或者free之后,

 

char *dp = malloc(A_CONST);
free(dp);
dp = NULL;

 

http://en.wikipedia.org/wiki/Null_pointer

有宏定义为

#ifndef NULL
#ifdef __cplusplus
#define NULL    0
#else
#define NULL    ((void *)0)
#endif
#endif

在C++里被定义为 0;没有定义__cplusplus的话,指向一个值为0的 void型指针。 

 2.Void * 定义一个指针,是确确实实存在地址的一个指针,仅仅是没有指定具体的形如int *, byte *, float *等类型。所以是指针类型为空的指针。

 

3.野指针 Wild Pointer

一般产生方式:

定义一个指针,没有初始化,如:

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 */
}

更多说明参考http://en.wikipedia.org/wiki/Wild_pointer

4. 垂悬指针Dangling Pointer

国内基本上将垂悬指针和野指针等同一个概念了。

产生原因:地址失效

如,访问有效期结束,导致,地址失效

{
   char *dp = NULL;
   /* ... */
   {
       char c;
       dp = &c;
   } /* c falls out of scope */
     /* dp is now a dangling pointer */
}

地址被释放,导致地址失效

int f(int i)
{
    char *p = NULL, *p2;
    p = (char *)malloc(1000);    /* get a chunk */
    p2 = p;              /* copy the pointer */
    /* use the chunk here */
    safefree((void **)&p);       /* safety freeing; does not affect p2 variable */
    safefree((void **)&p);       /* this second call won't fail */
    char c = *p2;       /* p2 is still a dangling pointer, so this is undefined behavior. */
    return i + c;
}

更多说明参考http://en.wikipedia.org/wiki/Dangling_pointer  在wiki上和Wild Pointer在同一条。

 

posted @ 2013-09-22 15:06  水上云天  阅读(453)  评论(0编辑  收藏  举报