C/C++ Arena

Step 3 of 9

Return heap memory from a function

A stack array dies when its function returns, so returning its address is a bug (a dangling pointer):

int *bad(void) {
    int a[3] = {1, 2, 3};
    return a;       // a is destroyed here!
}

Heap memory survives until someone frees it, so a function can create it and hand it back. The caller then owns it and must free it.

Your turn: write int *range(int n) returning a new heap array {0, 1, ..., n-1}.

Previous: Size decided at runtime Next: calloc and strdup-style copies