C ยท Chapter 34 of 45

C Dynamic Memory (malloc/free)

Dynamic memory allocation lets a program request memory while it's running, rather than at compile time. The <stdlib.h> functions malloc(), calloc(), realloc() and free() manage this heap memory.

Unlike local variables, dynamically allocated memory persists until you explicitly free it, so it's your responsibility to release it when it's no longer needed to avoid memory leaks.

Syntax
type *p = malloc(n * sizeof(type));
free(p);

Allocating memory

malloc(size) reserves a block of `size` bytes and returns a pointer to it (or NULL on failure). calloc(count, size) does the same but also zero-initializes the memory.

Freeing memory

Once you're done with dynamically allocated memory, call free(pointer) to return it to the system. Forgetting to free memory causes a memory leak.

Example 1 (c)
#include <stdio.h>
#include <stdlib.h>

int main() {
  int *arr = malloc(3 * sizeof(int));
  arr[0] = 1; arr[1] = 2; arr[2] = 3;
  printf("%d\n", arr[1]);
  free(arr);
  return 0;
}
Output
2

malloc reserves space for 3 ints on the heap, used like a normal array, then freed.

Example 2 (c)
#include <stdio.h>
#include <stdlib.h>

int main() {
  int *p = malloc(sizeof(int));
  if (p == NULL) {
    printf("Allocation failed\n");
    return 1;
  }
  *p = 42;
  printf("%d\n", *p);
  free(p);
  return 0;
}
Output
42

Always check malloc's return value for NULL before using the pointer.

Key points

  • malloc() allocates uninitialized heap memory; calloc() zero-initializes it.
  • Always check malloc's return value for NULL to detect allocation failure.
  • free() releases memory back to the system when you're done with it.
  • Forgetting to free() causes memory leaks over a program's lifetime.
๐Ÿ’ก Note: Never use a pointer after calling free() on it โ€” this is called a 'dangling pointer' and causes undefined behavior.

๐Ÿ“ Quick Quiz

1. What does malloc() return if allocation fails?

2. What must you call when you're done with dynamically allocated memory?

3. What is it called when memory is never freed?