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

Scope of heap-allocated data

Scope of heap-allocated data

What you'll learn: Why data stored on the heap lives on even after a function finishes, unlike local variables.

The persistent storage

In C, local variables live on the stack. They are like sticky notes on a desk; as soon as you finish a task (exit a function), the notes are swept into the bin. Their "scope" is tied strictly to the curly braces {} where they were born.

Heap-allocated memory—created using malloc—is different. Think of the heap like a rental storage unit. When you request memory, the system gives you a key (a pointer) to a specific unit. Even if you leave the office or finish your current task, that storage unit remains yours until you explicitly go back and vacate it.

Bypassing function boundaries

Because heap memory isn't tied to the stack, it allows you to "ship" data out of a function. Normally, if you create an array inside a function, that array is destroyed the moment the function returns. By using the heap, the data stays alive as long as you have the pointer to find it.

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

int* create_secret_number() {
    // This pointer is local (stack), but the memory it 
    // points to is external (heap).
    int *heap_ptr = malloc(sizeof(int));
    
    *heap_ptr = 42;
    
    // We return the address. The variable 'heap_ptr' dies,
    // but the '42' stays alive in the storage unit.
    return heap_ptr; 
}

int main() {
    int *my_data = create_secret_number();
    
    // Even though create_secret_number() is finished,
    // the data is still there!
    printf("The number is: %d", *my_data);
    
    // We must manually destroy the storage unit
    free(my_data);
    
    return 0;
}

The trade-off: Manual control

This "long-distance" scope is incredibly powerful for building complex data structures like linked lists or trees that need to grow and shrink over time. However, it comes with a responsibility: since the compiler won't automatically clean up the heap when a function ends, you are the only one who knows when that data is no longer needed. If you lose the pointer before calling free(), that memory stays reserved but unreachable—a situation known as a memory leak.

Key takeaway

Heap-allocated data has "manual scope"; it exists from the moment you call malloc() until the moment you call free(), regardless of which function created it.