Lesson 100 +10 XP

Allocating Memory with malloc

Allocating Memory with malloc

malloc (memory allocation) reserves a block of bytes for you.

The basic call

int *p = (int *)malloc(sizeof(int));
  • sizeof(int) says how many bytes.
  • The result is typed to int *.
  • It returns NULL when memory runs out.

Allocating an array

int *numbers = (int *)malloc(5 * sizeof(int));
numbers[0] = 10;
numbers[1] = 20;

You get 5 int slots, used like an array.

Always check for NULL

if (ptr == NULL) {
    printf("Memory allocation failed!");
    return 1;
}

Free when done

free(numbers);

TL;DR

  • malloc(size) allocates bytes at runtime.
  • Cast the result to your pointer type.
  • Check for NULL before use.
  • Free everything you allocate.