For working professionals
For fresh graduates
More
5. Array in C
13. Boolean in C
18. Operators in C
33. Comments in C
38. Constants in C
41. Data Types in C
49. Double In C
58. For Loop in C
60. Functions in C
70. Identifiers in C
81. Linked list in C
83. Macros in C
86. Nested Loop in C
97. Pseudo-Code In C
100. Recursion in C
103. Square Root in C
104. Stack in C
106. Static function in C
107. Stdio.h in C
108. Storage Classes in C
109. strcat() in C
110. Strcmp in C
111. Strcpy in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
If you’ve spent any time coding in C, you’ve likely come across the term dangling pointer in C. It sounds harmless—maybe even a little funny—but in reality, it's one of those pesky bugs that can cause unpredictable behavior, memory corruption, crashes, or worse: subtle logical errors that take hours (or days) to trace.
In C, you're given direct access to memory via pointers. This power comes with the risk of using memory incorrectly. A dangling pointer in C is a pointer that continues to reference a memory location after the object it points to has been deleted or deallocated. To understand this more accurately, you should explore dynamic memory allocation in C programming.
In this blog, we’re going to break down exactly what a dangling pointer in C is, how it’s created, and most importantly, how to avoid it. We'll walk through code examples, explain the risks, and offer practical strategies, just like they are provided in top-rated software development courses. So, if you’ve ever scratched your head at a segmentation fault or weird behavior after free(), you’re in the right place.
A dangling pointer in C is a pointer that doesn’t point to a valid memory location. It may still hold a memory address, but the data at that address is either invalid or has been reclaimed by the system. Using such pointers can lead to undefined behavior, making your program crash or behave unpredictably.
In simpler terms, a dangling pointer in C is like a house key you kept after the house was demolished—it doesn’t open anything anymore, but it still looks like it should.
Let’s look at why a dangling pointer in C is dangerous:
Unlock a high-paying job with the following full-stack development courses:
Let’s look at a basic code snippet that causes a dangling pointer in C.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int *)malloc(sizeof(int)); // Allocating memory
*ptr = 42; // Assigning value
printf("Value before free: %d\n", *ptr); // Output: 42
free(ptr); // Memory is deallocated
printf("Value after free: %d\n", *ptr); // Undefined behavior! Dangling pointer in use
return 0;
}
Output
Value before free: 42
Value after free: [undefined or garbage value, or crash]
Explanation
In this example, `ptr` initially points to dynamically allocated memory holding the value `42`. After we call `free(ptr);`, the memory is returned to the system. But `ptr` still holds the address. So when we try to access `*ptr`, we’re using a dangling pointer in C—the program might still run, or it might crash, or worse, silently produce garbage.
In short, the object is gone, but the pointer still lingers. That’s the danger.
Additionally, before you move forward the details, it’s recommended to understand the following C concepts:
To prevent errors effectively, you first need to understand how they happen. A dangling pointer in C doesn’t just appear out of nowhere—it’s the result of specific coding practices, often subtle ones. Let’s dig deep into the common scenarios that lead to a dangling pointer in C, and understand what exactly goes wrong in each case.
There are three primary ways a dangling pointer in C is typically created:
This is the most obvious and frequent cause. When you allocate memory dynamically using `malloc()` or `calloc()`, you must eventually free that memory using `free()`. However, if you continue to use the pointer after the memory has been freed, you’re accessing memory you no longer legally own—this is the essence of a dangling pointer in C.
Example: Accessing Freed Memory
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int *)malloc(sizeof(int)); // Allocate memory for an integer
*ptr = 100; // Store a value
printf("Before freeing: %d\n", *ptr); // Valid access
free(ptr); // Memory is now deallocated
// This is now a dangling pointer in C
printf("After freeing: %d\n", *ptr); // Undefined behavior
return 0;
}
Output
Before freeing: 100
After freeing: [could be garbage value or crash]
Explanation
After the `free(ptr)` call, the memory that `ptr` points to has been released back to the system. While `ptr` still holds the address, accessing it is illegal. This results in a dangling pointer in C. The program may still compile and run, but the result is unpredictable—it might crash, produce garbage, or silently corrupt other data.
A subtle yet dangerous way to create a dangling pointer in C is by returning the address of a local (stack-allocated) variable from a function. Stack variables are destroyed automatically once the function returns, so any pointer to them becomes invalid.
Also read, what is variable in C to gain a better insight about local variable.
Example: Returning Local Address
#include <stdio.h>
int* createPointer() {
int local = 42; // Local variable
return &local; // Returning address of a local variable
}
int main() {
int *ptr = createPointer();
// ptr is now a dangling pointer in C
printf("Dangling pointer value: %d\n", *ptr); // Undefined behavior
return 0;
}
Output
Dangling pointer value: [garbage or crash]
Explanation
In this case, the pointer `ptr` receives the address of `local`, which ceases to exist after `createPointer()` returns. So, `ptr` becomes a dangling pointer in C. The memory location might be reused, causing the value at that address to be overwritten by something else—leading to potentially serious bugs.
Just like returning a local variable's address from a function, you can also create a dangling pointer in C by assigning the address of a scoped variable to a pointer and then using that pointer after the variable’s scope ends.
Example: Out-of-Scope Variable
#include <stdio.h>
int* getScopedPointer() {
int temp = 88; // Scoped variable
int *ptr = &temp; // Pointer to it
return ptr; // Returning the pointer
}
int main() {
int *dangling = getScopedPointer();
// dangling is now a dangling pointer in C
printf("Value from dangling pointer: %d\n", *dangling); // Undefined behavior
return 0;
}
Output
Value from dangling pointer: [garbage or segmentation fault]
Explanation
The variable `temp` exists only during the execution of `getScopedPointer()`. Once it exits, `temp` is gone. However, we’ve returned its address and stored it in `dangling`, making it a dangling pointer in C. This is a subtle error and hard to trace because the code might work “sometimes” during testing—making it even more dangerous in production.
Reallocating memory can also cause a dangling pointer in C if you lose the original pointer before assigning the result of `realloc()` to a new one safely.
Example: Unsafe Reallocation
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int *)malloc(2 * sizeof(int));
ptr[0] = 10;
ptr[1] = 20;
// realloc might move memory. If it fails, original memory is leaked
ptr = realloc(ptr, 4 * sizeof(int)); // Safe in this case, but if not saved correctly, original ptr becomes dangling
printf("Value after realloc: %d\n", ptr[0]);
free(ptr); // Clean up
return 0;
}
Expected Output (if realloc succeeds):
Value after realloc: 10
Output (if realloc fails)
NULL
Explanation
In this example, if you had written something like:
realloc(ptr, 4 * sizeof(int)); // Not assigning it back
Then the original `ptr` would become a dangling pointer in C if `realloc()` moves the memory. Always capture the result of `realloc()` in a temporary pointer first to avoid this.
Now that we’ve seen how dangerous a dangling pointer in C can be—and how it’s commonly created—let’s talk about prevention. The good news? Avoiding a dangling pointer in C is very possible with some disciplined practices and habits.
Let’s walk through key techniques to keep your pointers safe, stable, and sane.
One of the simplest and most effective ways to avoid a dangling pointer in C is to explicitly set the pointer to `NULL` right after calling `free()`.
Example: Nullifying After Freeing
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int *)malloc(sizeof(int));
*ptr = 30;
free(ptr); // Memory freed
ptr = NULL; // Pointer nullified to avoid dangling pointer in C
// Safe: won't crash, just doesn't do anything
if (ptr != NULL) {
printf("Value: %d\n", *ptr);
} else {
printf("Pointer is NULL, safe from dangling pointer in C.\n");
}
return 0;
}
Output
Pointer is NULL, safe from dangling pointer in C.
Explanation
After freeing, setting the pointer to `NULL` ensures you don't accidentally use it. In C, dereferencing a `NULL` pointer will crash immediately (e.g., segmentation fault), making the bug obvious—unlike silently using a dangling pointer in C, which may go unnoticed.
Also read about if-else statement in C and nested if-else statement to efficiently develop the code logic.
Improper use of `realloc()` is another sneaky way a dangling pointer in C can arise. If `realloc()` fails, it returns `NULL` and the original memory block remains valid. But if you overwrite your original pointer with `NULL`, you've now lost access to that memory—creating a leak and potentially leaving you with a dangling pointer in C.
Example: Safe realloc()
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int *)malloc(2 * sizeof(int));
ptr[0] = 1;
ptr[1] = 2;
// Use a temporary pointer
int *temp = realloc(ptr, 4 * sizeof(int));
if (temp != NULL) {
ptr = temp; // Safe to assign
ptr[2] = 3;
ptr[3] = 4;
printf("Values: %d, %d, %d, %d\n", ptr[0], ptr[1], ptr[2], ptr[3]);
} else {
// realloc failed; original ptr is still valid
printf("Memory reallocation failed. Avoided dangling pointer in C.\n");
free(ptr); // Always clean up
}
return 0;
}
Output (on success)
Values: 1, 2, 3, 4
This one’s a classic mistake. Returning the address of a local (stack) variable creates a dangling pointer in C because the variable goes out of scope when the function ends.
What to Do Instead?
Fixed Version Example
#include <stdio.h>
#include <stdlib.h>
int* getSafePointer() {
int *ptr = (int *)malloc(sizeof(int)); // Dynamically allocated
*ptr = 55;
return ptr; // This is safe
}
int main() {
int *safePtr = getSafePointer();
printf("Safe value: %d\n", *safePtr);
free(safePtr); // Always free your allocations
return 0;
}
Output
Safe value: 55
Another reliable way to create a dangling pointer in C is to reference a variable after it has gone out of scope.
Fix: Define Variables in the Right Scope
Ensure that any variable a pointer references will outlive the pointer itself.
#include <stdio.h>
void assignPointer(int p) {
static int safeVar = 77; // static retains scope beyond function
*p = &safeVar;
}
int main() {
int *ptr = NULL;
assignPointer(&ptr);
printf("Value from static variable: %d\n", *ptr); // Safe
return 0;
}
Output
Value from static variable: 77
Explanation
The use of `static` ensures `safeVar` persists even after `assignPointer()` exits, avoiding the dangling pointer in C issue.
Also explore article on compiling C program on Linux to master programming across operating systems.
If you need to return a reference that lasts longer than a function's scope—but don’t want to dynamically allocate memory—`static` or global variables are an option. Just be cautious with concurrency and side effects.
The dangling pointer in C is one of those bugs that can be both elusive and catastrophic. It creeps in silently, often during seemingly harmless memory operations—accessing freed memory, returning local addresses, or misusing scoped variables. And once it shows up, it can crash your program, corrupt your data, or worse—cause undefined behavior that’s hard to trace.
You've seen how a dangling pointer in C is created and why it's so dangerous. More importantly, you've learned practical, real-world techniques to prevent it. From nullifying pointers after freeing them, to using safer realloc() patterns, to understanding variable scopes—these strategies will help you write safer, cleaner C code.
In a language as powerful and low-level as C, pointer safety is your responsibility. With great power comes great responsibility—and now, with great understanding, you’re better equipped to tame the dangers of the dangling pointer in C.
No, a dangling pointer in C is a pointer that was once valid but now points to deallocated or out-of-scope memory. A wild pointer, on the other hand, is a pointer that has not been initialized at all. Both are dangerous, but a dangling pointer was previously valid, while a wild pointer never was.
A dangling pointer in C points to a previously valid memory location that is no longer accessible. A null pointer, on the other hand, is explicitly set to NULL and does not point to any memory. Accessing a null pointer results in a crash, but it’s safer than silently using a dangling pointer.
Dangling pointers are typically caused by freeing dynamically allocated memory and then continuing to use the pointer, returning the address of local variables, or using pointers to variables that have gone out of scope. These situations leave the pointer pointing to memory that is no longer valid for access.
No, most C compilers do not detect dangling pointers at compile time. Dangling pointers are a runtime issue, and because they still hold valid-looking addresses, they don’t raise immediate flags. Tools like Valgrind or AddressSanitizer can help detect them during execution by tracking memory usage and pointer behavior.
Using a dangling pointer in C can lead to segmentation faults, memory corruption, data loss, and undefined program behavior. The worst part is that some bugs caused by dangling pointers might not crash immediately, making them hard to detect and debug. These bugs can silently alter program logic and corrupt data.
Always set your pointer to NULL after calling free(). This prevents accidental use of freed memory. Before accessing any pointer, check if it is NULL. This small habit makes it easier to identify invalid access attempts and helps reduce the chance of introducing a dangling pointer in C into your code.
Accessing a dangling pointer in C invokes undefined behavior. This can cause the program to crash, return garbage values, or even seem to work normally while causing subtle bugs. Since the memory pointed to might have been reallocated elsewhere, you're essentially tampering with something you no longer own or control.
Global variables themselves don’t go out of scope and typically don’t become dangling pointers. However, if a global pointer variable is set to point to dynamically allocated memory that is later freed, and you continue to use that pointer, it becomes a dangling pointer in C just like any other.
Yes, static variables are not destroyed when a function exits, so returning their address does not create a dangling pointer in C. They're stored in a different memory segment that persists for the program’s lifetime, making them a safe alternative when a function needs to return a persistent reference.
Valgrind is a powerful memory debugging tool that helps detect memory leaks, use-after-free errors, and dangling pointers in C. It tracks allocated memory and alerts you when your code accesses memory that has already been freed or is no longer valid, helping you catch bugs during testing and development.
Yes, dangling pointer issues are not limited to C. In C++, you can also have dangling pointers when deleting dynamically allocated memory with delete or delete\[], and continuing to use the pointer. Modern C++ encourages using smart pointers, which automatically manage memory and significantly reduce the chance of dangling pointer errors.
Take a Free C Programming Quiz
Answer quick questions and assess your C programming knowledge
Author|900 articles published
Previous
Next
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.