Stack vs Heap Memory in C: Automatic Call Frames vs Dynamic Allocation
Comparing stack vs heap memory allocation is a key concept in the systems programming of C to avoid stack overflow, memory leaks, and dangling pointers. Stack memory is used to store automatic local variables and function call frames in a contiguous LIFO memory region whose size is automatically controlled by the CPU stack pointer, which provides ultra fast allocation, is restricted in size (typically 1 MB to 8 MB) and has a scope bound lifetime. In contrast, heap memory is dynamically allocated at run-time using malloc, calloc or realloc from a large process address space and remains available after return from the functions that created it until it is explicitly freed with free(), at the expense of allocator bookkeeping overhead and fragmentation.
Stack vs Heap in C: Memory Layout, Allocation Speed & Lifetimes — Technical Overview
Comparing stack vs heap memory allocation is a key concept in the systems programming of C to avoid stack overflow, memory leaks, and dangling pointers. Stack memory is used to store automatic local variables and function call frames in a contiguous LIFO memory region whose size is automatically controlled by the CPU stack pointer, which provides ultra fast allocation, is restricted in size (typically 1 MB to 8 MB) and has a scope bound lifetime. In contrast, heap memory is dynamically allocated at run-time using malloc, calloc or realloc from a large process address space and remains available after return from the functions that created it until it is explicitly freed with free(), at the expense of allocator bookkeeping overhead and fragmentation.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int stack_var = 42;
int *heap_var = malloc(sizeof(*heap_var));
if (heap_var != NULL) {
*heap_var = 99;
printf("stack_var=%d, *heap_var=%d\n", stack_var, *heap_var);
free(heap_var);
}
return 0;
}
Runnable C example
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int stack_var = 42;
int *heap_var = malloc(sizeof(*heap_var));
if (heap_var != NULL) {
*heap_var = 99;
printf("stack_var=%d, *heap_var=%d\n", stack_var, *heap_var);
free(heap_var);
}
return 0;
}Expected Output
stack_var=42, *heap_var=99