C/C++ Arena

Step 1 of 9

Stack vs heap

So far every variable lived on the stack: it's created when its block starts and destroyed automatically when the block ends. Stack arrays need a size known up front, and they die when the function returns.

The heap is memory you request at runtime and give back when you're done:

#include <stdlib.h>

int *a = malloc(n * sizeof(int));   // room for n ints
if (a == NULL) { /* out of memory */ }
a[0] = 42;                          // use it like an array
free(a);                            // give it back

malloc returns NULL if it fails. Every malloc needs exactly one matching free.

Your turn: allocate room for n ints.

Next: Size decided at runtime