pointers-memory · intermediate · ~12 min

Allocate a range

Allocate, initialise, and return heap memory.

Challenge

Allocate a heap array, fill it with a counting sequence, and return it for the caller to use and free.

Task

Implement int *make_range(int n) that mallocs an array of n ints, fills it with 0, 1, ..., n-1, and returns the pointer. No main — the grader calls it and frees the result.

Input

n — the number of ints to allocate (zero and negative counts are rejected).

Output

On success, returns a malloc-ed int* of length n holding 0..n-1. The caller owns and frees it. Return NULL for invalid/empty requests or allocation failure, as specified in the contract below.

Example

make_range(5)   ->   {0, 1, 2, 3, 4}
make_range(1)   ->   {0}

Rules

  • The returned block is heap-allocated; the caller is responsible for free.

Why this matters

Drill: practice one contract before combining it with other skills.

Input format

n — the number of ints to allocate (zero and negative counts are rejected).

Output format

On success, returns a malloc-ed int* of length n holding 0..n-1. The caller owns and frees it. Return NULL for invalid/empty requests or allocation failure, as specified in the contract below.

Constraints

For n <= 0 or an unrepresentable allocation size return NULL. Otherwise allocate n ints holding 0..n-1. Return NULL on allocation failure. Caller owns and frees a successful result.

Starter code

#include <stdlib.h>

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

Common mistakes

Allocating pointer-sized elements; writing through NULL; returning automatic storage.

Edge cases to handle

n=1; zero/negative n; integer extremes in size checks; forced allocation failure.

Up next

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