</>EmbeddedInterview

How do you check whether a pointer is NULL safely?

Easy"Coding: Memory & String Functions"
#include <stddef.h>

int sensor_read(const struct sensor *s, int *out)
{
    if (s == NULL || out == NULL)          /* check before every dereference of external input */
        return -1;
    *out = s->value;
    return 0;
}

#define SAFE_FREE(p) do { free(p); (p) = NULL; } while (0)

Points: compare with NULL (or !p) before dereferencing; checking after *p is too late, and the compiler may even remove the later check because dereferencing NULL is undefined behaviour. Set pointers to NULL after freeing to turn use-after-free into a detectable NULL access. A NULL check cannot detect dangling or wild pointers (they are non-NULL). On Cortex-M, add an MPU region at address 0 so a missed check faults instead of silently reading flash.