Skip to content
Justice Tech School

NULL and Dangling Pointers

Set pointers to NULL after free and check before use.

Example
#include <stdio.h>
#include <stdlib.h>

int main(void) {
  int *p = malloc(sizeof *p);
  *p = 5;
  free(p);
  p = NULL;
  printf("%s\n", p == NULL ? "safe" : "dangling");
  return 0;
}

Result

safe

Exercise

Safe empty pointer.

int *p = ;

Quiz Test

Why set p = NULL after free?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.