pointers-memory · intermediate · ~15 min
Heap allocation with `malloc` and ownership transfer to the caller.
Implement int *make_seq(size_t n) that allocates an array holding 1,2,...,n and returns a pointer to it. The caller is responsible for free(). If n is zero, return NULL (or any pointer to a zero-length region).
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.
#include <stdlib.h>
#include <stddef.h>
int *make_seq(size_t n) {
/* TODO */
return NULL;
}
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).
N == 0 — malloc(0) is implementation-defined; check the spec. Very large N — malloc may fail.
O(N) to fill.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.