Right Click to Search

Friday, June 25, 2024

Causes of Dangling Pointer in C


Dangling Pointer in C
  1. Dangling pointers arise when an object is deleted or deallocated, without modifying the value of the pointer, so that the pointer still points to the memory location of the deallocated memory.
  2. In Short Pointer Pointing to Non-Existing Memory Location is called  Dangling Pointer.
There are different ways where Pointer acts as "Dangling Pointer".

Way 1 :Using Free / De allocating Memory
#include<stdlib.h>
{
    char *ptr = malloc(Constant_Value);
    .......
    .......
    .......
    free (ptr);      /* ptr now becomes a dangling pointer */
}
  1. Character Pointer is Declared in the first Step.
  2. After some statements we have deallocated memory which is previously allocated.
  3. As soon as "Memory is Deallocated Pointer is now Dangling".
  4. Problem : If any pointer is pointing the memory address of any variable but after some variable has deleted from that memory location while pointer is still pointing such memory location. Such pointer is known as dangling pointer and this problem is known as dangling pointer problem.
How to Ensure that Pointer is no Longer Dangling ?
#include<stdlib.h>
{
    char *ptr = malloc(Constant_Value);
    .......
    .......
    .......
    free (ptr);  /* ptr now becomes a dangling pointer */
    ptr = NULL   /* ptr is no more dangling pointer */
}
  • After Deallocating memory Initialize Pointer to NULL so that pointer is now no longer dangling .
  • Initializing Pointer Variable to NULL Value means "Now Pointer is not pointing to anywhere"
Way 2 :Out of Scope
#include<stdlib.h>
void main()
 {
   char *ptr = NULL;
   .....
   .....
   {
       char ch;
       ptr = &ch;
   } 
   .....   /* dp is now a dangling pointer */
}
  1. Character Pointer is Declared in the first Step.
  2. Pointer Variable 'ptr' is pointing to Character Variable 'ch' declared in the inner block .
  3. 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"
Way 3 : Function Call
int * func ( void )
{
    int num = 14;
    /* ... */
    return #
}
Attempts to read from the pointer may still 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.

Tags / Keywords : |

Stumble
Delicious
Technorati
Twitter
Facebook

0 Comments:

Post a Comment

Your Feedback :This is Growing Site and Your Feedback is important for Us to improve the Site performance & Quality of Content.Feel Free to contact and Please Provide Name & Contact Email

 

Learn C Programming Copyright © 2010 LKart Theme is Designed by Lasantha, Free Blogger Templates