- 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.
- In Short Pointer Pointing to Non-Existing Memory Location is called 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 */ }
- Character Pointer is Declared in the first Step.
- After some statements we have deallocated memory which is previously allocated.
- As soon as "Memory is Deallocated Pointer is now Dangling".
- 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.
#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"
#include<stdlib.h> void main() { char *ptr = NULL; ..... ..... { char ch; ptr = &ch; } ..... /* dp is now a dangling pointer */ }
- Character Pointer is Declared in the first Step.
- 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"
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.int * func ( void ) { int num = 14; /* ... */ return # }
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