Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Dangling Pointer Block Diagram
3.
Cases where dangling pointers arise
3.1.
De-allocation of memory
3.2.
Function call
3.3.
Variable is out of scope
4.
FAQs
5.
Key takeaways
Last Updated: Mar 27, 2024

Dangling Pointer

Author Shivam Verma
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

In general, Dangling means to hang freely. So as the name suggests, a dangling pointer is a pointer that points to an invalid memory or a memory that is not valid anymore. The daggling pointer arises when the referencing object is deleted or deallocated, and your pointer still points to a memory location. It creates a problem because the pointer points to the memory that is not available. When we try to dereference such type of pointer, it shows the undefined behavior and can cause the segmentation fault. 

Recommended Topic, Sum of Digits in C and Data Structure.

Dangling Pointer Block Diagram

As shown in the above diagram, Pointer1 and Pointer2 are the pointers that point to the allocated objects Object1 and Object2, respectively. But Pointer3 is a pointer that points to a memory object that has been already deallocated. So Pointer3 becomes a dangling pointer. When you try to access the Pointer3, you will get an undefined result or segmentation fault.

Also see: C Static Function and  Short int in C Programming

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Cases where dangling pointers arise

There are three different cases where dangling pointers arise:

  • De-allocation of memory
  • Function call
  • Variable is out of scope

Let us see all three cases with some examples. 

De-allocation of memory

We use library functions like malloc() and calloc() for allocating a memory block and free() function for deallocating a memory block. As soon as we deallocate a memory block using the free() function and do not modify the pointer value, the pointer pointing to the memory block becomes a dangling pointer.

Let us understand this concept through a program.

#include<stdio.h>  
int main()  
{  
   int *ptr=(int *)malloc(sizeof(int));  
   ......
   ......
   ......
   free(ptr);  // After free call, ptr becomes a dangling pointer
   return 0;  
} 

In the above program, the malloc() function will allocate a memory block to the pointer 'ptr', and the free() function will deallocate a memory. When the free(ptr) function executes, the memory is deallocated for pointer 'ptr', which becomes a dangling pointer.

This dangling pointer can be resolved by initializing the pointer 'ptr' to NULL after deallocating memory. So that the pointer then points to nothing. 

Here we modified the above program to resolve this dangling pointer issue.

#include<stdio.h>  
int main()  
{  
   int *ptr=(int *)malloc(sizeof(int));  
   ......
   ......
   ......
   free(ptr);  // After free call, ptr becomes a dangling pointer
   ptr=NULL;   // the pointer ptr is not dangling anymore as it is pointing to nothing
   return 0;  
}

Function call

In this case, the dangling pointer problem arises when we do not declare a local variable as static in the function body.

Let us understand this concept through a program and try to implement on an online C compiler.

#include <stdio.h>
int *fun()
{
	int k=15;
	return &k;
}
int main()
{
	int *ptr=fun();
	fflush(stdin);
	printf("%d", *ptr);  // ptr points to something which is not valid anymore
	return 0;
}

Output

Garbage value

In the above program, when the fun() function is called, then the control moves to fun() function from the main() function, and the function fun() returns the address of the 'k' variable. but When control comes back to the main() function, the variable 'k' is no longer available. So the 'ptr' pointer becomes a dangling pointer as it points to the deallocated memory. The dangling pointer problem can be solved by declaring k as a static variable.

Here we modified the above program to resolve this dangling pointer issue.

#include<stdio.h>
int *fun()
{
	static int k=15;
	return &k;
}
int main()
{
	int *ptr=fun();
	fflush(stdin);
	printf("%d", *ptr); 
	return 0;
}

Output

15

Variable is out of scope

The pointer becomes a dangling pointer when the variable it is pointing to goes out of scope.

Let us understand this concept through a program.

#include<stdio.h>
int main()
{
	int *ptr;
	{
		int k=15;
		ptr=&k;   // here ptr is not dangling pointer
	}
	printf("%d",*ptr);    // here ptr is dangling pointer as num is out of scope in this block
	return 0;
}

In the above program, when we try to use the 'ptr' pointer out of the inner scope, it becomes the dangling pointer because it points to the deallocated memory. The solution to this problem is to extend the scope of the variable that the pointer is pointing to.

Here we modified the above program to resolve this dangling pointer issue.

#include<stdio.h>
int main()
{
	int *ptr;
	int k=15;
	{
		ptr=&k; 
	}
	printf("%d",*ptr);   
	return 0;
}

Output

15


You can also read about the dynamic arrays in c.

FAQs

  1. How to avoid dangling pointer in C?
    We can avoid the dangling pointer errors by initializing the pointer to the NULL value. If we initialize the pointer to the NULL value, then the pointer will not point to the deallocated memory.
     
  2. What is a dangling pointer in C?
    A dangling pointer is a pointer that points to an invalid memory or a memory that is not valid anymore.
     
  3. What is the wild pointer in C?
    A pointer variable that is not initialized with any address before its first use is called a wild pointer. It is also known as a bad pointer because it holds the address of a random memory location. 

Key takeaways

In the C programming language, Dangling pointers are pointers that point to a memory location that has been deleted. This blog has discussed the dangling pointer and the cases where dangling pointers can occur. To learn more about pointers, visit Introduction to Pointers.

This blog is over now. We hope that this blog has helped you enhance your knowledge regarding Null pointers. If you would like to learn more, click here to read more blogs related to the C programming language.

Previous article
Null Pointer in C
Next article
Wild Pointer in C
Live masterclass