pointers-memory · intermediate · ~15 min

Allocate sequence 1..N

Heap allocation with `malloc` and ownership transfer to the caller.

Challenge

Implement int *make_seq(size_t n) that allocates an array holding 1,2,...,n and returns a pointer to it. The caller is responsible for free(). If n is zero, return NULL (or any pointer to a zero-length region).

Why this matters

Allocating a runtime-sized array is the simplest realistic use of malloc. It introduces the read-N, malloc(N), fill, free pattern that you'll repeat thousands of times.

Starter code

#include <stdlib.h>
#include <stddef.h>

int *make_seq(size_t n) {
    /* TODO */
    return NULL;
}

Common mistakes

Not checking malloc's return for NULL. Forgetting to free. Using sizeof(int*) instead of sizeof(int) (a 32-bit array on a 64-bit pointer-sized system would be twice as big — bug).

Edge cases to handle

N == 0 — malloc(0) is implementation-defined; check the spec. Very large N — malloc may fail.

Complexity

O(N) to fill.

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.