Dangling Pointers
Use-after-free dangers.
What Is a Dangling Pointer
A dangling pointer points to memory that has already been freed or is otherwise no longer valid.
Using it leads to undefined behavior: crashes, corruption, or silent bugs.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *p = malloc(sizeof(int));
*p = 5;
printf("%d\n", *p);
free(p);
p = NULL;
return 0;
}Use After Free
The most common cause is reading or writing through a pointer after free.
The block may have been reused for something else.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *p = malloc(sizeof(int));
*p = 42;
free(p);
/* Reading *p here would be use-after-free. */
p = NULL;
printf("avoided use-after-free\n");
return 0;
}All lessons in this course
- malloc and free
- calloc and realloc
- Memory Leaks
- Dangling Pointers