C++ Memory Model
Stack vs heap, memory layout
Interview Relevant: System programming
C++ Memory Model
Understanding how memory is organized.
Code Examples
Memory layout and storage duration.
cpp
1// Stack memory (automatic storage)
2void stackExample() {
3 int x = 10; // Stack
4 int arr[100]; // Stack
5} // Automatically freed
6
7// Heap memory (dynamic storage)
8void heapExample() {
9 int* p = new int(10); // Heap
10 delete p; // Must free manually
11}
12
13// Memory segments:
14// - Text: compiled code
15// - Data: global/static initialized variables
16// - BSS: global/static uninitialized (zero)
17// - Heap: dynamic allocation (grows up)
18// - Stack: local variables (grows down)
19
20// Static storage duration
21static int counter = 0; // Lives entire program
22
23// Thread-local storage (C++11)
24thread_local int threadCounter = 0;
25
26// Object layout
27struct Example {
28 char a; // 1 byte + 3 padding
29 int b; // 4 bytes
30 char c; // 1 byte + 3 padding
31}; // Total: 12 bytes (with padding)
32
33// Alignment
34alignas(16) int aligned; // 16-byte aligned