Bird
Raised Fist0
Embedded Cprogramming~5 mins

Stack vs heap in embedded context

Choose your learning style10 modes available
Introduction

Stack and heap are two ways your program stores data in memory. Knowing the difference helps you write better embedded programs that use memory safely and efficiently.

When you need temporary data that disappears after a function finishes, use the stack.
When you need memory that lasts longer or changes size during the program, use the heap.
When you want to avoid running out of memory in small embedded devices.
When you want to understand why your embedded program crashes or behaves oddly.
When you want to manage memory carefully to save power and space.
Syntax
Embedded C
/* Stack example: local variables inside a function */
void exampleFunction() {
    int localVariable = 10;  // Stored on stack
}

/* Heap example: dynamic memory allocation */
#include <stdlib.h>

void exampleHeap() {
    int *pointer = (int *)malloc(sizeof(int));  // Allocated on heap
    if (pointer != NULL) {
        *pointer = 20;
        free(pointer);  // Free heap memory
    }
}

The stack stores local variables and function calls. It grows and shrinks automatically.

The heap is used for dynamic memory you allocate and free manually using malloc and free.

Examples
This shows a simple local variable stored on the stack.
Embedded C
void stackExample() {
    int number = 5;  // Stored on stack
}
This shows how to allocate and free memory on the heap.
Embedded C
#include <stdlib.h>

void heapExample() {
    int *pointer = (int *)malloc(sizeof(int));
    if (pointer != NULL) {
        *pointer = 10;
        free(pointer);
    }
}
Stack can be very small if no local variables are used.
Embedded C
void emptyStackFunction() {
    // No local variables, stack usage is minimal
}
Allocating zero bytes on heap may return NULL or a pointer. Always check before use.
Embedded C
#include <stdlib.h>

void heapNullCheck() {
    int *pointer = (int *)malloc(0);  // May return NULL or valid pointer
    if (pointer != NULL) {
        free(pointer);
    }
}
Sample Program

This program shows how a variable is stored on the stack inside a function and how memory is allocated and freed on the heap. It prints values before and after to show the flow.

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

void printStackExample() {
    int localVariable = 42;  // Stored on stack
    printf("Stack variable value: %d\n", localVariable);
}

void printHeapExample() {
    int *heapVariable = (int *)malloc(sizeof(int));  // Allocate on heap
    if (heapVariable == NULL) {
        printf("Heap allocation failed\n");
        return;
    }
    *heapVariable = 99;
    printf("Heap variable value: %d\n", *heapVariable);
    free(heapVariable);  // Free heap memory
}

int main() {
    printf("Before stack example\n");
    printStackExample();
    printf("After stack example\n\n");

    printf("Before heap example\n");
    printHeapExample();
    printf("After heap example\n");

    return 0;
}
OutputSuccess
Important Notes

Time complexity: Accessing stack variables is very fast (constant time). Heap allocation and freeing can be slower and may fragment memory.

Space complexity: Stack size is limited and fixed per program. Heap size depends on available memory and can grow or shrink.

Common mistake: Forgetting to free heap memory causes memory leaks, which is bad for embedded devices with limited memory.

Use stack for small, short-lived data. Use heap for large or variable-sized data that needs to live longer.

Summary

The stack stores temporary data like local variables and function calls.

The heap stores dynamic data you allocate and free manually.

In embedded systems, managing stack and heap carefully prevents crashes and saves memory.

Practice

(1/5)
1. In embedded C, where are local variables inside functions typically stored?
easy
A. On the stack
B. On the heap
C. In flash memory
D. In CPU registers only

Solution

  1. Step 1: Understand local variable storage

    Local variables inside functions are temporary and exist only during function execution.
  2. Step 2: Identify stack usage in embedded C

    The stack is used to store temporary data like local variables and return addresses.
  3. Final Answer:

    On the stack -> Option A
  4. Quick Check:

    Local variables = stack [OK]
Hint: Local variables go on stack, dynamic memory on heap [OK]
Common Mistakes:
  • Confusing heap with stack for local variables
  • Thinking local variables are stored in flash
  • Assuming all variables are in CPU registers
2. Which of the following is the correct way to allocate memory dynamically in embedded C?
easy
A. int p = malloc(sizeof(int));
B. int *p = sizeof(int);
C. int *p = malloc(sizeof(int));
D. malloc(int p);

Solution

  1. Step 1: Recall malloc syntax

    malloc returns a pointer to allocated memory, so pointer variable is needed.
  2. Step 2: Check each option

    int *p = malloc(sizeof(int)); correctly assigns malloc's return to an int pointer. Others misuse types or syntax.
  3. Final Answer:

    int *p = malloc(sizeof(int)); -> Option C
  4. Quick Check:

    malloc returns pointer, assign to pointer [OK]
Hint: malloc returns pointer, assign to pointer variable [OK]
Common Mistakes:
  • Assigning malloc result to non-pointer variable
  • Using sizeof without malloc
  • Incorrect function call syntax
3. What will happen if you declare a large array inside a function in embedded C on a system with limited stack size?
medium
A. Stack overflow may occur causing a crash
B. Heap memory will be used automatically
C. The array will be stored in flash memory
D. The compiler will convert it to a global variable

Solution

  1. Step 1: Understand stack size limits

    Stack size is limited in embedded systems; large local arrays consume stack space.
  2. Step 2: Consequence of large stack allocation

    Allocating large arrays locally can exceed stack size, causing overflow and crash.
  3. Final Answer:

    Stack overflow may occur causing a crash -> Option A
  4. Quick Check:

    Large local arrays risk stack overflow [OK]
Hint: Large local arrays risk stack overflow in embedded [OK]
Common Mistakes:
  • Assuming heap is used automatically
  • Thinking large arrays go to flash
  • Believing compiler auto-converts locals to globals
4. Consider this code snippet in embedded C:
void func() {
  int *p = malloc(10 * sizeof(int));
  // ... use p ...
  // missing free(p);
}
What is the main problem here?
medium
A. Pointer p is not initialized
B. Stack overflow due to large local array
C. Syntax error in malloc usage
D. Memory leak because allocated heap memory is not freed

Solution

  1. Step 1: Analyze malloc usage

    Memory is allocated on the heap with malloc but never freed.
  2. Step 2: Identify consequences of missing free

    Not freeing heap memory causes memory leak, wasting limited embedded memory.
  3. Final Answer:

    Memory leak because allocated heap memory is not freed -> Option D
  4. Quick Check:

    Missing free causes memory leak [OK]
Hint: Always free malloc memory to avoid leaks [OK]
Common Mistakes:
  • Confusing stack overflow with memory leak
  • Thinking malloc syntax is wrong
  • Assuming pointer is uninitialized
5. In an embedded system with 2KB stack and 4KB heap, which approach is best to safely allocate a 1KB buffer for temporary data?
hard
A. Declare a local array of 1KB inside a function
B. Use malloc to allocate 1KB on the heap and free after use
C. Declare a global 1KB array to avoid stack and heap
D. Use a static local array inside the function

Solution

  1. Step 1: Evaluate stack usage for large buffer

    1KB local array uses half the stack, risking overflow in embedded systems.
  2. Step 2: Consider heap allocation safety

    Allocating 1KB on heap with malloc is safer; heap is larger and managed manually.
  3. Step 3: Compare global and static arrays

    Global/static arrays use fixed memory but reduce flexibility and increase RAM usage always.
  4. Final Answer:

    Use malloc to allocate 1KB on the heap and free after use -> Option B
  5. Quick Check:

    Heap allocation safer for large temporary buffers [OK]
Hint: Use heap malloc for large temporary buffers in embedded [OK]
Common Mistakes:
  • Using large local arrays risking stack overflow
  • Ignoring freeing heap memory
  • Assuming global arrays are always best
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard