Example 1 — Safe free and a static fix
Reset the pointer after free, and return a static instead of a local.
#include <stdio.h>
#include <stdlib.h>
static int *counter(void) {
static int c = 0;
c++;
return &c;
}
int main(void) {
int *p = malloc(sizeof *p);
if (!p) return 1;
*p = 7;
printf("value = %d\n", *p);
free(p);
p = NULL;
if (p == NULL) printf("pointer reset to NULL\n");
printf("counter: %d\n", *counter());
printf("counter: %d\n", *counter());
return 0;
} How It Works
- After
free(p)the old address is invalid, sopis reset toNULL. - A later
if (p)check can now catch accidental use. - A
staticlocal lives for the whole program, so returning its address is safe.
