2009年3月20日 星期五

What is a dangling pointer?

A Dangling Pointer arises when you use the address of an object after its lifetime is over. This may occur in situations like returning addresses of the automatic variables from a function or using the address of the memory block after it is freed
{
char *cp = NULL;
/* ... */
{
char c;
cp = &c;
} /* c falls out of scope */
/* cp is now a dangling pointer */
}

To resolve dangling pointer issue:

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

沒有留言:

張貼留言