Back to: C Tutorials For Beginners and Professionals
Dangling Pointer in C Language with Examples
In this article, I will discuss Dangling Pointer in C Language with Examples. Please read our previous articles discussing Void Pointer in C Language with Examples. A dangling pointer in C programming is a pointer that doesn’t point to a valid memory location.
Dangling Pointer in C Language:
The most common bugs related to pointers and memory management in the C Programming Language are Dangling/Wild Pointers. Sometimes, as a programmer, we forget to initialize the pointer with a valid address, and when we do so, this type of uninitialized pointer is known as a dangling pointer.
A dangling pointer occurs at the time of the object destruction when the object is deleted or de-allocated from memory without modifying the value of the pointer. In this case, the pointer is pointing to the memory, which is de-allocated.
The pointer variable that points to an inactive or dead memory location is called the Dangling Pointer. In other words, we can say that a pointer pointing to a memory location that has been deleted (or freed) is called a dangling pointer in the C language. For a better understanding, please have a look at the below diagram.
In the above diagram, you can see we have three-pointers and observe that Pointer 3 is a dangling pointer. Pointer 1 and Pointer 2 are the pointers that point to the allocated objects, i.e., Object 1 and Object 2, respectively, whereas Pointer 3 is a dangling pointer as it points to a deleted object.
How to Create a Dangling Pointer in C Language?
In C Programming Language, there are three different ways where we can make a pointer acts as a dangling pointer. They are as follows:
- Deallocation of Memory: When the memory to which the pointer was pointing is freed or deallocated, the pointer is not set to NULL. Thus, it still points to the memory location, which is no longer valid. So, setting the pointer to NULL after freeing it is important to avoid this issue.
- Function Call: When a pointer points to a local variable in a function, and the function call is over. As local variables get destroyed after a function call, the pointer pointing to such a variable becomes dangling.
- Variable Goes Out of Scope: When a pointer points to a variable, and the variable goes out of scope, It becomes a dangling pointer.
Creating Dangling Pointer By De-Allocating the Memory in C Language:
Deallocating the memory that is pointed by a pointer causes a dangling pointer. In the below example, we have created an integer pointer. Then, we call the free function by passing the pointer. Once we call the free function, the pointer ptr becomes a dangling pointer.
#include <stdlib.h> #include <stdio.h> int main() { int *ptr = (int *)malloc(sizeof(int)); free(ptr); }
The solution to the above Problem:
In C Programming Language, the dangling pointer errors can be avoided by initializing the pointer to a NULL value. If we assign the NULL value to the pointer, then the pointer will not point to the de-allocated memory. Instead, the pointer is not pointing to any memory location. So, in the below example, after calling the free function, we initialize the pointer with a NULL value; hence, it is no longer a Dangling Pointer.
#include <stdlib.h> #include <stdio.h> int main() { int *ptr = (int *)malloc(sizeof(int)); free(ptr); ptr = NULL; }
Creating Dangling Pointer By Function Call in C Language:
In C Language, the pointer pointing to the local variable becomes dangling when the local variable is not static. In the below example, the variable x is a local variable and goes out of scope once the execution of the fun() function is completed. Inside the main method, the pointer p is pointing to something that does not exist anymore; hence, the pointer ptr becomes a dangling pointer.
#include<stdio.h> int *fun() { int x = 5; return &x; } int main() { int *ptr = fun (); printf ("%d", *ptr); return 0; }
Output: A Garbage Address
In the above program, ptr is called a Dangling Pointer because according to the storage class of C, by default, any variable storage class specifier is auto, and the lifetime of the auto variable is within the body only. But in the program, the control is passed back to the main function, and still, the pointer is pointing to that inactive variable only.
The solution to the above Problem:
The solution of the dangling pointer is in place of creating an auto variable, create a static variable because the lifetime of the static variable is the entire program. Let us modify the program as follows, where we make the variable x static. Once we make variable x static, the variable x has scope throughout the program. So, you need to remember that the pointer pointing to the local variable doesn’t become a dangling pointer when the local variable is static.
#include<stdio.h> int *fun() { static int x = 5; return &x; } int main() { int *ptr = fun(); printf ("%d", *ptr); return 0; }
Output: 5
Creating a Dangling Pointer by Variable Goes Out of Scope in C Language:
When the variable goes out of scope, the pointer becomes dangling. In the below example, first, we created one pointer ptr. Then, with the variable scope, we initialized the pointer. Once the variable goes out of scope, it becomes a dangling pointer.
#include<stdio.h> void main() { int *ptr; //Variable scope started { int ch; ptr = &ch; } //Variable scope ended // Now ptr is dangling pointer printf ("%d", *ptr); return 0; }
Dangling Pointer Key Characteristics
Dangling pointers in C and other programming languages are a common source of bugs and security vulnerabilities. They possess certain key characteristics that can help in identifying and preventing issues related to them:
- Invalid Memory Reference: A dangling pointer refers to a memory location that has been freed or is no longer valid. This means any attempt to access or manipulate the data at that memory location can lead to undefined behavior.
- Caused by Deallocation: Dangling pointers often occur after an object is deallocated (e.g., using free in C), but the pointer is not set to NULL. The pointer still holds the address of the memory location, even though that memory may now be used for something else.
- Scope-Related Issues: They can also occur when a pointer points to a variable’s memory location that goes out of scope. For instance, a pointer to a function’s local variable becomes dangling once the function exits.
- Undefined Behavior: Dereferencing a dangling pointer leads to undefined behavior. This can manifest in various ways, such as program crashes, corrupt data, or unexpected program behavior.
- Hard to Detect: Dangling pointers can be challenging to detect, especially in large and complex programs, as they may not always cause immediate, visible issues.
- Security Risk: They pose a significant security risk. Attackers can exploit dangling pointers to execute arbitrary code, leading to security breaches.
- Memory Leaks: While not directly causing memory leaks, dangling pointers can be associated with them. If a pointer is left dangling and then overwritten without freeing the initially pointed-to memory, it can result in a memory leak.
To prevent dangling pointer issues:
- Always set pointers to NULL after freeing the memory they point to.
- Be cautious about the scope of variables when returning pointers from functions.
- Employ good memory management practices and tools (like static analyzers) that can help identify and mitigate these issues.
In the next article, I will discuss the Function Pointer in C language. In this article, I try to explain Dangling Pointer in C Language with Examples. I hope you enjoy this Dangling Pointer in C Language with Examples article. I would like to have your feedback. Please post your feedback, questions, or comments about this article.
About the Author: Pranaya Rout
Pranaya Rout has published more than 3,000 articles in his 11-year career. Pranaya Rout has very good experience with Microsoft Technologies, Including C#, VB, ASP.NET MVC, ASP.NET Web API, EF, EF Core, ADO.NET, LINQ, SQL Server, MYSQL, Oracle, ASP.NET Core, Cloud Computing, Microservices, Design Patterns and still learning new technologies.