Table of contents
1.
Introduction
2.
What is a Dangling Pointer in C?
3.
Dangling Pointer Block Diagram
4.
Difference Ways of Pointer Act as a Dangling Pointer
4.1.
De-allocation of memory
4.2.
Function call
4.3.
C
4.4.
C
4.5.
Variable is out of scope
4.6.
C
4.7.
C
5.
How to Avoid Dangling Pointer Errors in C?
6.
Frequently Asked Questions
6.1.
What is a dangling pointer in C++?
6.2.
How do you identify a dangling pointer?
6.3.
How to fix a dangling pointer?
6.4.
What is the wild pointer in C?
7.
Conclusion
Last Updated: Nov 4, 2024

Dangling Pointer in C

Author Shivam Verma
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In C programming, managing memory effectively is crucial for developing robust and efficient applications. One of the common pitfalls that can arise during memory management is the phenomenon of a dangling pointer. A dangling pointer occurs when a pointer continues to reference a memory location that has been deallocated or freed, leading to undefined behavior and potential program crashes. Understanding dangling pointers is essential for preventing memory-related errors and ensuring the stability of your code.

Dangling Pointer in C

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

What is a Dangling Pointer in C?

A dangling pointer in C refers to a pointer that does not point to a valid object or memory location. This situation arises when the object that the pointer was pointing to has been deallocated or freed, yet the pointer still holds the address of that memory location. Accessing or dereferencing a dangling pointer can lead to undefined behavior, crashes, or data corruption, making it a critical issue in memory management.

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

Difference Ways of Pointer Act as a Dangling Pointer

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.

  • C

C

#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;
}
You can also try this code with Online C Compiler
Run Code

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.

  • C

C

#include<stdio.h>
int *fun()
{
static int k=15;
return &k;
}
int main()
{
int *ptr=fun();
fflush(stdin);
printf("%d", *ptr);
return 0;
}
You can also try this code with Online C Compiler
Run Code

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.

  • C

C

#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;
}
You can also try this code with Online C Compiler
Run Code

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.

  • C

C

#include<stdio.h>
int main()
{
int *ptr;
int k=15;
{
ptr=&k;
}
printf("%d",*ptr);  
return 0;
}
You can also try this code with Online C Compiler
Run Code

Output

15


You can also read about the dynamic arrays in c.

How to Avoid Dangling Pointer Errors in C?

Avoiding dangling pointer errors in C is crucial for maintaining the stability and reliability of your applications. Here are several strategies and best practices to help prevent these issues:

1. Set Pointers to NULL After Freeing

After deallocating memory using free(), always set the pointer to NULL. This prevents the pointer from unintentionally referencing invalid memory. A NULL pointer can be easily checked before dereferencing.

int *ptr = (int *)malloc(sizeof(int)); // Dynamically allocate memory
free(ptr); // Free the allocated memory
ptr = NULL; // Set pointer to NULL to avoid dangling pointer

2. Avoid Returning Addresses of Local Variables

Never return the address of a local variable from a function, as the variable will cease to exist once the function exits. Instead, allocate memory dynamically or pass pointers to allocated memory.

int* func() {
    int *localVar = (int *)malloc(sizeof(int)); // Dynamically allocate memory
    *localVar = 5; // Assign a value
    return localVar; // Return the pointer to allocated memory
}

3. Use Smart Pointers (in C++)

If you are working with C++, consider using smart pointers (std::unique_ptr, std::shared_ptr) provided by the Standard Template Library (STL). Smart pointers manage memory automatically and reduce the risk of dangling pointers.

#include <memory>

std::unique_ptr<int> ptr = std::make_unique<int>(5); // Automatically manages memory
// No need to explicitly free memory; it will be released when ptr goes out of scope

4. Limit Pointer Scope

Limit the scope of pointers whenever possible. By keeping pointers within the smallest possible scope, you reduce the risk of them becoming dangling. Use local variables as much as possible and return values rather than pointers.

void safeFunction() {
    int localVar = 10; // Local variable
    int *ptr = &localVar; // Pointer to local variable
    // Use ptr within this function only
}

5. Use malloc() or calloc() for Dynamic Memory

When you need to return pointers from functions, use malloc() or calloc() to allocate memory dynamically. This ensures that the memory remains valid until it is explicitly freed.

int* createArray(int size) {
    int *array = (int *)malloc(size * sizeof(int)); // Allocate memory for an array
    return array; // Return the pointer to the allocated memory
}

6. Implement a Memory Management Strategy

For complex applications, consider implementing a memory management strategy, such as using a memory pool or reference counting. This helps track allocations and deallocations more effectively.

7. Regularly Audit and Test Your Code

Regularly audit your code for potential dangling pointers, and use tools like Valgrind to detect memory leaks and dangling references. Testing can help identify edge cases where pointers might become dangling

Frequently Asked Questions

What is a dangling pointer in C++?

A dangling pointer in C++ refers to a pointer that points to a memory location that has been deallocated, leading to undefined behavior.

How do you identify a dangling pointer?

You can identify a dangling pointer by checking if it points to memory that has been freed or if it references a local variable that is out of scope.

How to fix a dangling pointer?

To fix a dangling pointer, set it to nullptr after freeing memory or ensure it does not reference deallocated or invalid memory locations.

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. 

Conclusion

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.

Live masterclass