tags:

views:

138

answers:

2

How can the below code result in a dangling pointer.

{
    char *cPointer = malloc ( some constant number );
    /* some code */
    free ( cPointer );      
    cPointer = NULL;        
    /* some code */
}
+3  A: 

If the first "some code" copies the pointer value from cPointer to some other pointer variable, and the second "some code" uses that other pointer variable, it will be in trouble.

If the first "some code" generates an exception so the free is never reached, it will leak memory.

Windows programmer
Assume the some code does nothing related to the pointer, if i dont give the cPointer = NULL; statement does that mean i have a dangling pointer in cPOinter?
ckv
@viswanathan, perhaps, you would want to edit your question, and make sure that your wording doesn't allow answers you consider incorrect.
Pavel Shved
If you remove the cPointer = NULL; statement then cPointer will be a dangling pointer, but it will only cause problems if you use it. The programmer's purpose in assigning NULL is to help catch unintended uses, i.e. to help find bugs and debug them.
Windows programmer
+14  A: 

It can't.

This would:

char * a = malloc(556);
char * b = a;
free(a);
a = NULL;

b is now dangling pointer, because the object it pointed to it's gone but b still stores address to memory where the object used to be, you get funny results when you try to access it - it depends if the memory has been reused or is untouched.

stefanB