Dangling pointers and Wild pointers

今天听到野指针与智能指针的名词,google了下,wikipedia解释:

Concept 

Dangling pointers arise when an object is deleted or deallocated, without modifying the value of the pointer, so that the pointer still points to the memory location of the deallocated memory. As the system may reallocate the previously freed memory to another process, if the original program then dereferences the (now) dangling pointer, unpredictable behavior may result, as the memory may now contain completely different data. This is especially the case if the program writes data to memory pointed by a dangling pointer, a silent corruption of unrelated data may result, leading to subtle bugsthat can be extremely difficult to find, or cause segmentation faults (*NIX) or general protection faults (Windows).

 

Cause of dangling pointers

{
   
char *dp = NULL;
   
/* ... */
   {
       
char c;
       dp 
= &c;
   } 
/* c falls out of scope */
     
/* dp is now a dangling pointer */
}
#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 */
    
/* ... */
}

Concept 

 Wild pointers arise when a pointer is used prior to initialization to some known state, which is possible in some programming languages. They show the same erratic behaviour as dangling pointers, though they are less likely to stay undetected.

Cause of wild pointers

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

 for more:

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

原文地址:https://www.cnblogs.com/no7dw/p/2052508.html