</>EmbeddedInterview

How do you detect memory leaks with an allocation table?

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

#define MAX_ALLOCS 256
typedef struct { void *p; size_t size; const char *file; int line; } rec_t;
static rec_t table[MAX_ALLOCS];

void *dbg_malloc(size_t n, const char *file, int line)
{
    void *p = malloc(n);
    if (p) {
        for (int i = 0; i < MAX_ALLOCS; i++)
            if (table[i].p == NULL) { table[i] = (rec_t){ p, n, file, line }; break; }
    }
    return p;
}

void dbg_free(void *p)
{
    for (int i = 0; i < MAX_ALLOCS; i++)
        if (table[i].p == p) { table[i].p = NULL; break; }
    free(p);
}

void dbg_report_leaks(void)
{
    for (int i = 0; i < MAX_ALLOCS; i++)
        if (table[i].p)
            printf("LEAK %zu bytes from %s:%d\n", table[i].size, table[i].file, table[i].line);
}

#define MALLOC(n) dbg_malloc((n), __FILE__, __LINE__)
#define FREE(p)   dbg_free(p)

Points: record every allocation with its call site, remove it on free, and dump what is left at a checkpoint (end of a test, or periodically on a device). Add a lock if used from several threads. Finding a leak "in given code" usually means spotting an early return or error path that skips free, or a pointer overwritten before being freed.