Menu
Coddy logo textTech

Stack vs. Heap Memory

Part of the Logic & Flow section of Coddy's C journey — lesson 31 of 63.

When your C program runs, it uses two distinct regions of memory: the stack and the heap. Understanding the difference between these memory areas is crucial for effective C programming, especially when working with pointers and dynamic memory allocation.

The stack is used for static memory allocation. This is where your local variables, function parameters, and function call information are stored. The stack is managed automatically by the system - when you declare a local variable, memory is allocated on the stack, and when the variable goes out of scope, that memory is automatically freed.

void function() {
    int x = 10;  // Allocated on the stack
    char arr[100];  // Also allocated on the stack
    // Memory is automatically freed when function ends
}

The heap is used for dynamic memory allocation. This is a larger pool of memory that you can request during program execution.

Unlike the stack, the heap requires manual management - you must explicitly request memory and later release it when you're done. This gives you more control but also more responsibility.

The key difference is management: stack memory is automatic and limited in size, while heap memory is manual and much larger. In the upcoming lessons, you'll learn how to work with heap memory using functions like malloc() and free().

Cheat sheet

C programs use two distinct memory regions:

Stack: Used for static memory allocation. Stores local variables, function parameters, and function call information. Memory is managed automatically - allocated when variables are declared and freed when they go out of scope.

void function() {
    int x = 10;  // Allocated on the stack
    char arr[100];  // Also allocated on the stack
    // Memory is automatically freed when function ends
}

Heap: Used for dynamic memory allocation. Larger pool of memory that requires manual management - you must explicitly request and release memory using functions like malloc() and free().

Key difference: Stack memory is automatic and limited in size, while heap memory is manual and much larger.

Try it yourself

This lesson doesn't include a code challenge.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow