Skip to content
Justice Tech School

malloc and free

malloc reserves heap memory and free releases it. Check for NULL and free once.

Example
#include <stdio.h>
#include <stdlib.h>

int main(void) {
  int *a = malloc(3 * sizeof *a);
  if (!a) return 1;
  for (int i = 0; i < 3; i++) a[i] = i * i;
  printf("%d %d\n", a[1], a[2]);
  free(a);
  return 0;
}

Result

1 4

Exercise

Release memory.

(a);

Quiz Test

What happens if you forget free?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.