Skip to content
FollowtheDamnCode

malloc and calloc

Getting memory when you need it.

6 minute read

Big idea

Arrays have a size fixed when you write the code. malloc asks for memory while the program runs, in whatever size you need right then — on the heap.

Two kinds of memory

  • Stack — ordinary variables. Created when a function starts, gone when it returns. Sizes are fixed in the code.
  • Heap — memory you ask for with malloc and give back with free. It lives until you free it, and its size can come from user input.

malloc

#include <stdlib.h>

int n = 5;
int *nums = malloc(n * sizeof(int));
if (nums == NULL) {
    printf("Out of memory\n");
    return 1;
}
  • malloc(bytes) — reserves that many bytes and returns their address (or NULL if it can't).
  • n * sizeof(int) — room for n ints. Always use sizeof — never guess that an int is 4 bytes.
  • The result is used exactly like an array: nums[0], nums[i].
  • malloc doesn't clear the memory — it holds leftover garbage until you write to it.

Watch it

calloc: zeroed memory

int *counts = calloc(n, sizeof(int));

calloc(count, size) reserves count × size bytes and sets every byte to 0. Use it when you want to start from zero — counters, tallies, flags:

Count letter frequencies with calloc
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int *counts = calloc(26, sizeof(int));
    if (counts == NULL) return 1;
    const char *text = "hello world";
    for (int i = 0; text[i] != '\0'; i++) {
        if (text[i] >= 'a' && text[i] <= 'z') {
            counts[text[i] - 'a']++;
        }
    }
    for (int i = 0; i < 26; i++) {
        if (counts[i] > 0) printf("%c:%d ", 'a' + i, counts[i]);
    }
    printf("\n");
    free(counts);
    return 0;
}
output
d:1 e:1 h:1 l:3 o:2 r:1 w:1 

Run and edit it in the app.

Watch calloc at work

Always check for NULL

When memory runs out, malloc and calloc return NULL. Writing through NULL crashes. One if after every allocation.

Which call reserves room for 10 doubles?

Think of it like

The stack is your desk: fixed space, cleared when you leave. The heap is a storage unit you rent by size — it's yours until you hand back the key, and nobody clears it for you.

🕷️ Spidey-sense: I never know how many hostages there'll be, so I can't pre-weave the net. I spin a web at run-time, sized to the crowd — that's malloc. And I cut it down after (free), or the city fills with old webs.

Key terms

  • Heap — Memory requested at run time; it lives until freed.
  • Stack — Memory for ordinary local variables; freed automatically.
  • malloc(bytes) — Reserves memory, contents undefined.
  • calloc(count, size) — Reserves memory set to zero.

Check yourself

Where does malloc'd memory live?

How do malloc and calloc differ?

What must you check after every malloc?