The classic memory bugs in C
Leak, double free, dangling pointer and off-by-one — shown so you recognize them.
#include <stdlib.h>
/* Leak: the early return never frees. */
int leaks(size_t n) {
int *values = malloc(n * sizeof(int));
if (values == NULL) {
return 0;
}
if (n > 100) {
return -1;
}
free(values);
return 1;
}
/* Fixed: one exit, and NULL after the free. */
int careful(size_t n) {
int *values = malloc(n * sizeof(int));
if (values == NULL) {
return 0;
}
int result = (n > 100) ? -1 : 1;
free(values);
values = NULL;
free(values);
return result;
}
How it works
- Every
mallocneeds exactly onefree, on every path. - Setting the pointer to NULL after freeing makes a double free harmless.
- A dangling pointer is the return of a dead local's address.
Keywords and builtins used here
NULLcarefulifintleaksreturnsize_tsizeof
The run, in numbers
- Lines
- 27
- Characters to type
- 450
- Tokens
- 122
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 73 seconds.
Step 2 of 4 in Ownership & mistakes, step 16 of 25 in Pointers & memory.