Tuesday, July 10, 2012

Dangling Pointer

C / C++ programmers should be extra cautious while handling pointers. Re-using a freed & nullified pointer causes application crash. The NULLIFIED pointer that causes the crash is named as Dangling Pointer.

Sample Code:

#include <stdio.h>
#include <string.h>

void main()
{
    char *pVal = new char[10];
    strcpy(pVal, "Hi Kingsley");

    printf("\nPrint String : %s\n", pVal);

    delete [] pVal;
    pVal = NULL; // Pointer Nullified
   
    strcpy(pVal, "Hi Kingsley"); // pVal is 'Dangling Pointer'. Copying string to it crashes the Application
}

No comments:

Post a Comment