Dangling Pointers in C – Explained with Output & Syntax Highlighting
Dangling Pointers in C – Explained with Output & Syntax Highlighting
A dangling pointer is a pointer that points to a memory location that has been deallocated or is no longer valid. Accessing such memory leads to undefined behavior.
π How Do Dangling Pointers Occur?
- Using memory after
free()
- Returning addresses of local variables from a function
- Accessing out-of-scope stack variables
π Example 1: Using Memory After free()
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int*) malloc(sizeof(int));
*ptr = 10;
printf("Before free: %d\n", *ptr);
free(ptr); // Memory is freed
// Dangling pointer usage
printf("After free (dangling): %d\n", *ptr); // Undefined behavior
return 0;
}
Output (may vary):
Before free: 10
After free (dangling): 10 ⛔ (Can be garbage or crash)
⚠️ The pointer
ptr
still holds the address of freed memory. This leads to undefined behavior.
π Example 2: Returning Address of Local Variable
int* badFunction() {
int a = 42;
return &a; // Address of local variable
}
int main() {
int *ptr = badFunction();
printf("Dangling value: %d\n", *ptr); // Undefined behavior
return 0;
}
Output (unreliable):
Dangling value: ???
Why? The variable a
is destroyed after badFunction()
ends, but its address is still used.
π Example 3: Pointer to Out-of-Scope Variable
void test() {
int *ptr;
{
int x = 7;
ptr = &x;
}
// x is now out of scope
printf("%d\n", *ptr); // Dangling
}
✅ Safe Practice: Nullify After Free
int main() {
int *ptr = (int*) malloc(sizeof(int));
*ptr = 99;
printf("Value: %d\n", *ptr);
free(ptr);
ptr = NULL; // ✅ Safe: prevents accidental use
return 0;
}
Output:
Value: 99
π§― Tips to Avoid Dangling Pointers
- Set pointer to
NULL
afterfree()
- Never return address of local variables
- Use tools like
Valgrind
to detect issues - Avoid accessing out-of-scope memory
π Visual Representation
+-------------+ +----------------+ | Pointer | ───▶ | Memory Block | +-------------+ +----------------+ ↓ [ free(ptr) called ] +-------------+ +----------------+ | Pointer | ───▶ | FREED/GARBAGE | +-------------+ +----------------+
π‘ Practice Task
Write a program that allocates memory, frees it, and then mistakenly uses the pointer. Fix it by setting the pointer to NULL
. Try running it with valgrind
(Linux users).
π Conclusion
Dangling pointers are silent killers in C. They are hard to debug and can crash your program or worse—corrupt data. By understanding when and how they occur, and using best practices, you can write safer, more stable C programs.
Comments
Post a Comment