C/C++ Arena

Memory leaks, dangling pointers and double frees

The classic C memory bugs, what causes them, and how to find them with AddressSanitizer and Valgrind.

None of these reliably crash, which is what makes them dangerous. Compile with -fsanitize=address -g while developing and the program stops at the exact line, or run it under valgrind.

Example

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

int main(void) {
    char *buf = malloc(8);
    if (!buf) return 1;
    buf[0] = 'o';
    buf[1] = 'k';
    buf[2] = '\0';
    printf("%s\n", buf);
    free(buf);
    buf = NULL;
    free(buf);
    return 0;
}

Output:

ok

Watch it run: Returning heap memory from a function

Practice it