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.

Dangling Pointer in C

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

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

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription