Dangling pointers
- C course
- Intermediate
- Lesson 10/116
- 5 min
Learn the dangling pointer concept and safety.
What is a dangling pointer?
A dangling pointer still points to memory that has been freed. After free(p) the value of p is unchanged; it still holds the old address.
Example: int *p = malloc(sizeof(int)); *p = 42; free(p); *p = 99;. Here the assignment after free is undefined behavior. The memory no longer belongs to you; it may be reused for another allocation. Such bugs often don't crash immediately; that makes them sneaky. valgrind reports them as Invalid write.
Set to NULL after free
A simple rule to reduce dangling pointer risk: free(p); p = NULL;. After setting the address to NULL, accidental *p use crashes the program; that's better than silent corruption.
Example: free(arr); arr = NULL;. Now you can use if (arr != NULL) to check whether the memory is valid. While accessing a NULL pointer is undefined behavior, on modern systems it crashes immediately (segfault); that helps you catch the bug early. This pattern is standard for long-lived and shared pointers.
Practice Safe free pattern
Allocate a single int with int *p = malloc(sizeof(int));. Assign *p = 42; and print it with printf("%d\n", *p). Free it with free(p);, then set p = NULL;. Inside if (p != NULL) put printf("still valid\n"); this must not print "still valid".
Starter code
#include <stdio.h>
#include <stdlib.h>
// Allocate one int, assign 42 and print
// Free it, set p to NULL
// Print only when p is not NULL
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *p = malloc(sizeof(int));
*p = 42;
printf("%d\n", *p);
free(p);
p = NULL;
if (p != NULL) printf("still valid\n");
return 0;
}Expected output
42
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is p's value after free(p)?
- Still holds the old address Correct answer
- Is deleted
- Becomes 0
- Becomes NULL
Explanation: p becomes a dangling pointer.
2 Match dangling and safe patterns
| Term | Meaning |
|---|---|
free(p); *p = 5; |
Dangling |
free(p); p = NULL; |
Safe |
if (p) *p = 5; |
Guarded |
free(NULL) |
Valid (no-op) |
3 Set to NULL after free
int *p = malloc(sizeof(int));
*p = 42;
free(p);
p = ____;
int *p = malloc(sizeof(int));
*p = 42;
free(p);
p = NULL;
Explanation: Setting NULL reduces the dangling pointer risk.