Lesson 100 +10 XP

Allocating Memory with malloc

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

The basic call


c
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


c
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


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

Free when done


c
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.