2009年7月31日 星期五

Dangling pointers

Dangling pointer就是一個記憶體指標,指向一個已經向系統申請free的記憶體位置

example 1:
#include 
{
char *cp = malloc ( A_CONST );
/* ... */
free
( cp ); /* cp now becomes a dangling pointer */
cp
= NULL; /* cp is no longer dangling */
/* ... */
}

example 2:

{
char *cp = NULL;
/* ... */
{
char c;
cp
= &c;
} /* c falls out of scope */
/* cp is now a dangling pointer
because the system has freed the memory of c.*/

}

Dangling pointers and wild pointers in computer programming are pointers that do not point to a valid object of the appropriate type.

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 bugs that can be extremely difficult to find, or cause segmentation faults (*NIX) or general protection faults (Windows)

reference:

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

沒有留言: