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

Introduction to the Heap segment

Introduction to the Heap segment

What you'll learn: You will understand the purpose of the Heap as a flexible pool of memory for data that needs to outlive a single function call or requires a custom size.

The "Messy Desk" vs. The "Storage Warehouse"

Think of the Stack like a small, organized desk. Whenever a function starts, it puts a folder on the desk. When the function ends, the folder is tossed in the bin. It’s fast, but space is limited, and you can't keep anything there once the job is done.

The Heap is a massive storage warehouse down the street. It doesn't care about function folders. If you want to store something in the warehouse, you call up the manager and ask for a specific amount of space. They give you a key (a pointer) to a locker. That locker remains yours until you explicitly call back and say, "I'm done with this."

Why do we need it?

In C, variables on the Stack have a "fixed" lifetime and size. If you create an array of 10 integers inside a function, that array vanishes the moment the function returns. Furthermore, you must know it’s exactly 10 integers before the program even runs.

The Heap solves two major problems:

  1. Dynamic Size: You can decide how much memory you need while the program is running (e.g., based on user input).
  2. Persistence: Data on the Heap stays there until you manually delete it. This allows you to create data in one function and safely use it in ten other functions later.

A look at Heap allocation

To use the Heap, we use functions like malloc (memory allocation). We tell the computer how many bytes we want, and it returns the starting address of that memory.

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

int main() {
    // We ask for enough heap space to hold one integer
    // 'intPtr' sits on the Stack, but it points to memory on the Heap
    int *intPtr = malloc(sizeof(int));

    if (intPtr != NULL) {
        *intPtr = 42; // Storing the value 42 in the Warehouse
        printf("Value on the heap: %d\n", *intPtr);
        
        // We must manually clean up the warehouse space
        free(intPtr);
    }

    return 0;
}

Because the Heap is managed by you, the programmer, it is more powerful but also more dangerous. If you lose the "key" (the pointer) without cleaning up, the memory stays occupied—this is what we call a memory leak.

Key takeaway

The Heap is a large, flexible pool of memory used for data that needs a custom size or must persist beyond the life of a single function.