Dangling Pointer in C
Dangling Pointer :
A dangling pointer in C is a sort of initialized pointer that exists because the programmer failed to initialize it with a proper address.
About Dangling Pointer :
- Dangling Pointers, as the name implies, are pointers that point to memory locations that have been released or removed by the application.
- Dynamic Memory Allocation principles are used while discussing the allocation and deallocation of memory blocks.
- In Dynamic Memory Allocation, we typically employ the C methods malloc(), calloc(), and free() to allocate and deallocate memory blocks.
- Consequently, a Dangling Pointer is created after we deallocate a memory block using the free() method.
Examples of Dangling Pointer :
Let,s see some example for better understanding the dangling pointer in C
Example 1
Run
#include<stdio.h> int *help(){ int val = 20; return &val; } int main() { int *ptr = help(); printf("%d", *ptr); return 0; }
Output :
Segmentation fault
What Happened Above?
In the program, when the control shifts to the context of the int *fun() when the fun() function is called, and the fun() function returns the address of the variable's 'val' variable.
The variable "val" is no longer available when control returns to the main() function context.
As a result, because the "ptr" pointer points to the de-allocated memory, we may claim that 'ptr' is a dangling pointer.
Avoiding Dangling Pointer :
- Initializing the pointer to the NULL value will prevent dangling pointer errors.
- The pointer will not point to the de-allocated memory if the NULL value is assigned to it.
- When a pointer is given the value NULL, it indicates that it is not pointing at any memory address.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment