pointers-memory · intermediate · ~12 min
Allocate, initialise, and return heap memory.
Allocate a heap array, fill it with a counting sequence, and return it for the caller to use and free.
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.
n — the number of ints to allocate (zero and negative counts are rejected).
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.
make_range(5) -> {0, 1, 2, 3, 4}
make_range(1) -> {0}
free.Drill: practice one contract before combining it with other skills.
n — the number of ints to allocate (zero and negative counts are rejected).
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.
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.
#include <stdlib.h>
int *make_range(int n) {
/* TODO */
return NULL;
}
Allocating pointer-sized elements; writing through NULL; returning automatic storage.
n=1; zero/negative n; integer extremes in size checks; forced allocation failure.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.