Memory Layout Overview

┌─────────────────────────────────────┐ ← High Address
│           STACK                     │
│  ↓ (grows downward)                 │
│  • Local variables                  │
│  • Function parameters              │
│  • Pointers to heap data            │
├─────────────────────────────────────┤
│           FREE SPACE                │
├─────────────────────────────────────┤
│           HEAP                      │
│  ↑ (grows upward)                   │
│  • Dynamic allocations (new)        │
│  • Large data structures            │
└─────────────────────────────────────┘ ← Low Address

02_01_memoryInCpp.png

Stack Memory

Characteristics

Examples

int main() {
    int a = 10;        // Stack
    char arr[100];     // Stack
    double d = 3.14;   // Stack

    return 0;  // All automatically destroyed
}

Why User Input Arrays Are Bad Practice

int n;
cin >> n;
int arr[n];  // BAD - Variable Length Array (VLA)
//VLAs are not part of standard C++, only a compiler extension (e.g., GCC).

Problems:

  1. Stack overflow risk - Limited stack size
  2. Non-standard C++ - May not work on all compilers
  3. Performance issues - Breaks compiler optimizations

Better alternatives:

// Option 1: Heap allocation
int* arr = new int[n];
delete[] arr;

// Option 2: Vector (recommended)
vector<int> arr(n);

Heap Memory