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.
Stack vs heap in embedded context
/* 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.
void stackExample() {
int number = 5; // Stored on stack
}#include <stdlib.h> void heapExample() { int *pointer = (int *)malloc(sizeof(int)); if (pointer != NULL) { *pointer = 10; free(pointer); } }
void emptyStackFunction() {
// No local variables, stack usage is minimal
}#include <stdlib.h> void heapNullCheck() { int *pointer = (int *)malloc(0); // May return NULL or valid pointer if (pointer != NULL) { free(pointer); } }
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.
#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; }
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.
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.