How can free () immediately after assigning NULL result in a dangling pointer?

How can the below code result in a dangling pointer.

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

      

+2


a source to share


2 answers


He can not.

It:



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

      

b now hangs a pointer because the object it pointed to but b

still stores the address in memory where the object used to be, you get funny results when you try to access it - it depends on whether it was reused or intact.

+14


a source


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



If the first "some code" throws an exception, so freedom is never achieved, it will leak memory.

+3


a source







All Articles