Dangling Pointer



Dangling Pointer

  • A dangling pointer is pointing to a memory location that has been deleted (or freed). The dangling pointer act as a different ways there are,
    • De-allocation of memory
    • Function Call
    • Variable goes out of scope

Read Also

De-allocation of memory

#include<stdlib.h>
void main()
{
    char *ptr = malloc(Constant_Value);
    free (ptr); //ptr now becomes a dangling pointer
}
  • First we have declared in the character pointer. After execution of some statements we have de-allocated memory which is allocated previously for the pointer.
  • Immediately memory is de-allocated for pointer, pointer becomes dangling pointer.

Function Call

int * func ( void )
{
    int num = 14;
    return #
}
  • The pointer may be return the correct value (1234) for a while after calling func, but any functions called thereafter will overwrite the stack storage allocated for num with other values and the pointer would no longer work correctly.
  • If a pointer to num must be returned, num must have scope beyond the function it might be declared as static.

Variable goes out of scope

#include<stdlib.h>
void main()
{
    char *ptr = NULL;
    {
        char ch;
        ptr = &ch;
    }//dp is now a dangling pointer
}
  • First we have declared in the Character Pointer.
  • Next the Pointer Variable ‘ptr’ is pointing to Character Variable ‘ch’ declared in the inner block .
  • As character variable is non-visible in Outer Block , then Pointer is still pointing to Same Invalid memory location in Outer block , then Pointer becomes “Dangling”.


Related Searches to Dangling Pointer