typestar

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

  1. malloc(n * sizeof(int)) reserves an array.
  2. A NULL return means allocation failed.
  3. The caller owns the memory and must free it.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 5 in Dynamic memory, step 10 of 25 in Pointers & memory.

← Previous Next →