Loading...

C essentialsPointers & Memory

Dangling pointers, leaks & buffer overflows

12 min lesson

Next
  • Pointer bugs are mistakes that make a pointer point to the wrong place, keep memory alive when it should be freed, or write outside an allocated block.
  • They matter because these bugs are common, hard to see, and can crash the program or corrupt data silently.
  • Think of a dangling pointer as an address to a house that was demolished: the note still exists, but the house is gone.
  • A dangling pointer points to memory that has been freed or to a local that no longer exists; using it is undefined behavior.
  • A memory leak happens when you lose the last pointer to a heap block without freeing it, so the memory stays reserved until the program ends.
  • A buffer overflow happens when you write past the end of an array or allocated block, corrupting nearby memory.
  • The computer does not check bounds or pointer validity for you, so these bugs often go unnoticed until something breaks.
  • The syntax that causes them looks normal: p after free, arr[size] beyond the end, or a pointer to a local returned from a function.
  • A realistic use of care: growing a buffer with realloc, copying strings with a size limit, and returning heap memory from functions instead of locals.
  • A surprising detail: reading freed memory often seems to work, which hides the bug until it fails at the worst moment.
  • The example program shows a safe pattern: check allocation, free exactly once, set the pointer to NULL, and copy strings with a length limit.
Keep in mind
  • Set pointers to NULL after free and never use them again.
  • Free every block exactly once; do not lose the only pointer to it.
  • Always check buffer sizes before writing, and use bounded copy functions.
  • Run memory checkers to catch these bugs early.
  • Avoiding these pitfalls makes you a professional. Excellent work!
main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    // Allocate a small buffer for a string
    size_t size = 16;
    char *name = malloc(size);
    // Check for allocation failure before using it
    if (name == NULL) {
        return 1;
    }

    // Copy with a length limit so we cannot overflow the buffer
    // The -1 leaves room for the null terminator
    strncpy(name, "Ada Lovelace", size - 1);
    // Make sure the string is terminated even if the copy filled the buffer
    name[size - 1] = '\0';
    // Print the safe copy
    printf("Name: %s\n", name);

    // Free the block exactly once
    free(name);
    // Set the pointer to NULL so it cannot be used by mistake
    name = NULL;
    // Check before dereferencing, even though we just set it
    if (name != NULL) {
        printf("This never runs.\n");
    } else {
        printf("Pointer is NULL, safe to stop.\n");
    }

    return 0;
}

What happens: Name: Ada Lovelace Pointer is NULL, safe to stop.

Breaking it down

Allocation

char *name = malloc(size);

Requests a 16-byte buffer. Always check for NULL before using the pointer.

Bounded copy

strncpy(name, "Ada Lovelace", size - 1);

Copies at most size - 1 characters so there is room for the terminator. This prevents a buffer overflow.

Terminator

name[size - 1] = '\0';

Guarantees the string ends properly even if the copy filled the whole buffer. Without it, printing reads past the end.

Free once

free(name);

Returns the block to the system. Freeing twice is a bug and can crash the program.

Set to NULL

name = NULL;

Prevents accidental use of the dangling pointer. A later dereference is caught by a NULL check or crashes clearly.

Common pointer pitfalls

PitfallCauseFix
Dangling pointerUse after freeSet to NULL after free
Double freeFree the same block twiceFree exactly once
Memory leakLost pointer without freeFree on all paths
Buffer overflowWrite past the endCheck sizes, use bounds
Return local addressStack frame disappearsReturn heap memory

A helpful analogy

A dangling pointer is like a note with the address of a house that was demolished. The note still exists, but the house is gone, so going there leads nowhere. A leak is renting a storage box and forgetting where you put the key, so nobody can use that box again.

Nesting rules

  • 1.After free, immediately set the pointer to NULL so any later use is obvious.
  • 2.Never write past the end of an array or allocated block; check the size first.
  • 3.Use bounded functions like strncpy, snprintf and memcpy with size limits.
  • 4.Free memory on every exit path, including error returns.

Common mistakes

Using a pointer after free

Avoid

free(p); printf("%d", *p); // dangling

Use instead

free(p); p = NULL;

The block may be reused by other code after free. Reading it gives garbage or crashes. Setting to NULL makes the mistake visible.

Freeing the same block twice

Avoid

free(p); free(p); // double free

Use instead

free(p); p = NULL; free(p); // free(NULL) is safe

The second free corrupts the heap manager. Freeing NULL is safe, so setting to NULL after the first free prevents double free.

Unbounded string copy

Avoid

char buf[8]; strcpy(buf, "too long for buf");

Use instead

char buf[8]; strncpy(buf, "too long", sizeof buf - 1); buf[sizeof buf - 1] = '\0';

strcpy writes past the buffer and corrupts nearby memory. Bounded copies prevent overflow.

Quick tips

  • •Set pointers to NULL right after free to make dangling use obvious.
  • •Run valgrind or -fsanitize=address to catch leaks and overflows automatically.
  • •Prefer snprintf over strcat for building strings safely.
  • •Try removing the NULL assignment after free and see whether a later check catches the bug.
  • •Keep allocation and free close together in the code so ownership is clear.
Previous
Next