</>EmbeddedInterview

Write code that shows a dangling pointer and a wild pointer, and how to fix them.

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

int *dangling_example(void)
{
    int *p = malloc(sizeof *p);
    *p = 42;
    free(p);
    /* *p = 7;    BUG: p is dangling (points to freed memory) */
    p = NULL;     /* fix: clear the pointer after free */

    int *q;
    /* *q = 5;    BUG: q is wild (uninitialised, random address) */
    q = NULL;     /* fix: always initialise */

    int local = 3;
    return &local;  /* BUG: returns a dangling pointer to a dead stack frame */
}

Dangling: pointer to an object whose lifetime has ended (freed heap memory, a returned local, an element of a vector/array that was reallocated). Wild: never initialised. Fixes: initialise all pointers, NULL them after free, never return addresses of locals (return by value, use static, or let the caller pass a buffer), and use sanitizers to catch the rest.