pointers-memory · intermediate · ~14 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.

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

Transfer exercise: apply the lesson to a complete function contract.

Input format

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

Output format

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.

Constraints

Return NULL for n=0, unrepresentable byte size, n>INT_MAX, or allocation failure. Otherwise return owned ints 1..n; caller frees.

Starter code

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

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

Common mistakes

Failing to check allocation or converting an unrepresentable size_t to int.

Edge cases to handle

Zero; one; allocation failure; check byte size and representable generated values.

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.