Course contentsShow
← C
Lesson 555 of 1,2198. Memory ManagementFree lesson

Invalid pointer increments before free

Invalid pointer increments before free

What you'll learn: Why shifting your pointer's address makes it impossible for the system to deallocate memory correctly.

The "Breadcrumb" problem

Imagine you are staying at a hotel. When you check in, the receptionist gives you the key to Room 101. To check out and "free" the room, you must return that specific key. If you try to hand back the key to Room 105, the computer system will crash or reject it because that isn't the room you were assigned.

In C, malloc gives you a "key"—a pointer to the very first byte of a block of memory. The operating system keeps a secret ledger that says: "The block starting at address X is Y bytes long." When you call free(), the system looks for address X in its ledger. If you have changed your pointer to point to X + 1, the system can't find it, and your program will likely crash with a "segmentation fault" or a "double free" error.

Losing your way

It is common to use a pointer to iterate through an array. If you increment that pointer, you lose your original reference to the start of the memory block.

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

int main() {
    // 1. Grab a block for 5 integers
    int *ptr = malloc(5 * sizeof(int));
    
    // 2. Moving the pointer (The Pitfall)
    for (int i = 0; i < 5; i++) {
        *ptr = i;
        ptr++; // Danger! 'ptr' no longer points to the start
    }

    // 3. This will crash or cause undefined behavior
    // The OS doesn't recognize this incremented address
    free(ptr); 

    return 0;
}

The solution: Keep a backup

To avoid this pitfall, never move the pointer that holds the "original address" from malloc. Instead, create a temporary "iterator" pointer or, even better, use array indexing.

If you use ptr[i], the base address of ptr stays exactly where it belongs. If you must use pointer arithmetic, create a copy like int *temp = ptr; and move temp instead. This ensures that when it is time to clean up, you still have the original "key" to give back to free().

Key takeaway

Always free() the exact address returned by malloc; if you move the pointer, you lose the ability to release that memory.