calloc and realloc

FunctionWhat it does
malloc(bytes)Reserve memory (it may contain leftover junk)
calloc(count, size)Reserve memory for count items, all set to 0
realloc(ptr, bytes)Make an existing block bigger (or smaller), keeping its contents
free(ptr)Give the memory back

calloc: memory that starts at zero

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

int main() {
    int *counts = calloc(5, sizeof(int));
    counts[3] = 7;
    for (int i = 0; i < 5; i++) {
        printf("%d ", counts[i]);
    }
    printf("\n");
    free(counts);
    return 0;
}

Output

0 0 0 7 0 

Tip: Use calloc when you need counters or totals that must start at 0.

realloc: growing a list

Suppose you're reading numbers until 0, without knowing how many will come. Start small, and when the list is full, make it twice as big with realloc:

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

int main() {
    int capacity = 2;
    int count = 0;
    int *list = malloc(capacity * sizeof(int));

    int x;
    scanf("%d", &x);
    while (x != 0) {
        if (count == capacity) {
            capacity *= 2;
            list = realloc(list, capacity * sizeof(int));
            printf("(grew to %d places)\n", capacity);
        }
        list[count] = x;
        count++;
        scanf("%d", &x);
    }

    printf("Read %d numbers:", count);
    for (int i = 0; i < count; i++) {
        printf(" %d", list[i]);
    }
    printf("\n");
    free(list);
    return 0;
}

Input (what the user types)

4 8 15 16 23 42 0

Output

(grew to 4 places)
(grew to 8 places)
Read 6 numbers: 4 8 15 16 23 42

Think of it like this: realloc is like moving to a bigger flat when your family grows: everything you own comes with you.

Remember: realloc may move your data to a new address. Always use the pointer it returns.

HOME LABS COMMUNITY DASHBOARD