pointers-memory · intermediate · ~15 min

Allocate sequence 1..N

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

Challenge

Allocate a heap array filled with 1, 2, ..., n and hand ownership to the caller.

Task

Implement int *make_seq(size_t n) that mallocs an array of n ints holding 1, 2, ..., n and returns a pointer to it. No main — the grader calls it.

Input

One size_t argument n (the number of elements; may be 0).

Output

A pointer to a freshly allocated array whose element i (0-based) is i+1. The caller is responsible for free(). If n is 0, return NULL (or any pointer to a zero-length region).

Example

make_seq(5)   ->   [1, 2, 3, 4, 5]
make_seq(0)   ->   NULL

Edge cases

  • n = 0: return NULL.
  • Return NULL if malloc fails.

Rules

  • Use malloc; the caller frees the result.

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.

Input format

One size_t argument n (may be 0).

Output format

A malloc'd array [1..n] owned by the caller; NULL when n is 0 or malloc fails.

Constraints

Use malloc; the caller frees.

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.