pointers-memory · intermediate · ~14 min
Heap allocation with `malloc` and ownership transfer to the caller.
Allocate a heap array filled with 1, 2, ..., n and hand ownership to the caller.
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.
One size_t argument n (the number of elements; may be 0).
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.
make_seq(5) -> [1, 2, 3, 4, 5]
make_seq(0) -> NULL
n = 0: return NULL.NULL if malloc fails.malloc; the caller frees the result.Transfer exercise: apply the lesson to a complete function contract.
One size_t argument n (the number of elements; may be 0).
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.
Return NULL for n=0, unrepresentable byte size, n>INT_MAX, or allocation failure. Otherwise return owned ints 1..n; caller frees.
#include <stdlib.h>
#include <stddef.h>
int *make_seq(size_t n) {
/* TODO */
return NULL;
}
Failing to check allocation or converting an unrepresentable size_t to int.
Zero; one; allocation failure; check byte size and representable generated values.
O(N) to fill.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.