Aral Code

Memory Lesson 14 of 16

C Dynamic Memory — malloc, calloc, realloc and free

Allocate memory while the program runs with malloc and calloc, grow it with realloc, release it with free, and avoid memory leaks and dangling pointers.

Normal arrays have a size fixed when you write the code. But what if the user decides how many students there are? Dynamic memory lets you request exactly the memory you need while the program is running.

Stack and heap

  • Stack: where normal local variables live. Fast and automatic, but limited, and variables disappear when the function ends.
  • Heap: a large pool of memory you request and release yourself with malloc and free. It stays until you free it.

malloc

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

int main(void) {
    int n = 5;
    int *grades = malloc(n * sizeof(int));   /* room for 5 ints */
    if (grades == NULL) {
        printf("Out of memory!\n");
        return 1;
    }
    for (int i = 0; i < n; i++) grades[i] = 80 + i * 3;
    for (int i = 0; i < n; i++) printf("%d ", grades[i]);
    printf("\n");
    free(grades);       /* give the memory back */
    return 0;
}

Output

80 83 86 89 92
  • malloc(bytes) (in <stdlib.h>) reserves memory and returns a pointer to it.
  • Always compute the size with sizeof: n * sizeof(int).
  • malloc returns NULL if there isn't enough memory. Check it.
  • The pointer can be used exactly like an array.
  • free releases the memory when you're done.

Size chosen by the user

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

int main(void) {
    int n;
    printf("How many students? ");
    if (scanf("%d", &n) != 1 || n <= 0) return 1;

    double *scores = malloc(n * sizeof *scores);
    if (!scores) return 1;

    double sum = 0;
    for (int i = 0; i < n; i++) {
        printf("Score %d: ", i + 1);
        scanf("%lf", &scores[i]);
        sum += scores[i];
    }
    printf("Average: %.2f\n", sum / n);
    free(scores);
    return 0;
}

Output

How many students? 3
Score 1: 88
Score 2: 92.5
Score 3: 79
Average: 86.50

sizeof *scores means "the size of what scores points to", which stays correct even if you later change the type.

calloc: zero-filled memory

calloc(count, size) works like malloc but sets every byte to zero:

int *tally = calloc(10, sizeof(int));   /* ten counters, all 0 */

realloc: growing an array

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

int main(void) {
    int capacity = 2, count = 0;
    int *list = malloc(capacity * sizeof(int));
    if (!list) return 1;

    for (int value = 10; value <= 60; value += 10) {
        if (count == capacity) {
            capacity *= 2;
            int *bigger = realloc(list, capacity * sizeof(int));
            if (!bigger) { free(list); return 1; }
            list = bigger;
            printf("(grew to %d slots)\n", capacity);
        }
        list[count++] = value;
    }
    for (int i = 0; i < count; i++) printf("%d ", list[i]);
    printf("\n");
    free(list);
    return 0;
}

Output

(grew to 4 slots)
(grew to 8 slots)
10 20 30 40 50 60

realloc resizes a block, copying the data to a new place if needed. Doubling the capacity each time is the same strategy Java's ArrayList and Python's lists use internally.

Common memory mistakes

MistakeWhat happens
Forgetting freeMemory leak: memory stays used until the program ends. In long-running programs, memory keeps growing.
Using memory after freeDangling pointer: unpredictable results or crashes
Freeing twiceCrash or corrupted memory
Not checking for NULLCrash when memory runs out
Writing past the endCorrupts other data (buffer overflow)

Every malloc needs one free

Think of heap memory like borrowing books from the library: each malloc borrows, and each free returns. Languages like Java, Python and JavaScript have a garbage collector that returns memory automatically. In C, it's your job, which is why C programs can be so fast and so tricky.

Quick Quiz

Check what you learned. Walang grade ito, practice lang. 🙂

1. Which header declares malloc and free?
2. What does malloc return when there isn't enough memory?
3. What is a memory leak?
4. What's the difference between malloc and calloc?

By Sir Reyel · Last updated 2026-12-04