malloc and free in C
Allocating memory on the heap at run time.
#include <stdlib.h>
int *make_squares(int n) {
int *items = malloc(n * sizeof(int));
if (items == NULL)
return NULL;
for (int i = 0; i < n; i++)
items[i] = i * i;
return items; /* caller must free() */
}
How it works
malloc(n * sizeof(int))reserves an array.- A
NULLreturn means allocation failed. - The caller owns the memory and must
freeit.
Keywords and builtins used here
NULLforifintmake_squaresreturnsizeof
The run, in numbers
- Lines
- 10
- Characters to type
- 205
- Tokens
- 64
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 40 seconds.
Step 1 of 5 in Dynamic memory, step 10 of 25 in Pointers & memory.