pointers-memory · intermediate · ~15 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 (or any pointer to a zero-length region).
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.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.
One size_t argument n (may be 0).
A malloc'd array [1..n] owned by the caller; NULL when n is 0 or malloc fails.
Use malloc; the caller frees.
#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.