Memory

Table of Contents

Memory

Here's a simplified diagram of memory, which houses both the stack and the heap.

Memory

When we add to the stack, the stack grows downward. When we add to the heap, the heap grows upward.

MemoryGrowth

Stack Allocation

When we create new variables, they go on the stack.

Abstractly, the stack is populated with items that we maintain or own, such as variables, or function calls.

Let's say we allocate a few variables in the C code below.

int main() {
    int x = 5;
  int y = 10;

  int arr[3] = {1,2,3};
}

A simple mental model might look something like this:

StackAllocation

Heap Allocation

The heap houses items that are not under our direct control.

We can directly put items on the heap and point to them.

Below, the variable x is on the stack, pointing to the value 5 on the heap.

int main() {
    int *x = 5;
}
HeapAllocation