Understanding Memory Layout: Stack and Heap
When programming in C, memory is allocated in two primary regions:
- Stack (automatic storage): Stores local variables and function call frames.
- Heap (dynamic storage): Used for dynamically allocated memory via malloc, calloc, or realloc.
#include <stdio.h>
#include <stdlib.h>
void example() {
int x = 10; // Stack variable
int *ptr = (int *)malloc(3 * sizeof(int)); // Heap allocation
ptr[0] = 100;
ptr[1] = 200;
ptr[2] = 300;
printf("x: %d\n", x);
printf("ptr[0]: %d, ptr[1]: %d, ptr[2]: %d\n", ptr[0], ptr[1], ptr[2]);
printf("ptr address: %p\n", (void *)ptr);
printf("&ptr: %p\n", (void *)&ptr);
printf("&x: %p\n", (void *)&x);
free(ptr);
}
int main() {
example();
return 0;
}
Expected Output
x: 10
ptr[0]: 100, ptr[1]: 200, ptr[2]: 300
ptr address: 0x601000
&ptr: 0x7ffd1238
&x: 0x7ffd1234
Stack Memory Layout
Function (Frame) Symbol Address Value
main ptr 0x7ffd1238 0x601000
example x 0x7ffd1234 10
Heap Memory Layout
Symbol Address Value
ptr[0] 0x601000 100
ptr[1] 0x601004 200
ptr[2] 0x601008 300
Notes and Observations
1. Pointer Value Relationship:
- `ptr` is a stack variable, but its value is an address in the heap.
- The value of `ptr` (0x601000) is the same as the address of the first item in the dynamically
allocated array (ptr[0]).
2. Stack vs Heap:
- Stack (automatic storage): Stores function call frames and local variables.
- Heap (dynamic storage): Stores dynamically allocated memory, which persists until manually
freed.
- Synonyms for Stack: Call Stack, Local Memory, Automatic Storage.
- Synonyms for Heap: Dynamic Memory, Free Store, Malloc Space.
3. Deallocation:
- Stack memory is automatically reclaimed when a function exits.
- Heap memory must be explicitly freed using free() to avoid memory leaks.
Final Thoughts:
- Understanding stack vs heap allocation is crucial for memory management.
- Always free allocated memory to prevent leaks.
- The stack follows a LIFO (Last In, First Out) principle.
- The heap allows flexible memory allocation, but must be managed carefully.