pointers-memory · intermediate · ~8 min
Use calloc for zeroed memory.
Allocate a zero-initialised int array using calloc, which both reserves and zeroes the memory in one call.
Implement int *zeros(int n) that returns an array of n ints allocated with calloc, so every element is 0. No main — the grader calls it and frees the result.
n — the number of ints to allocate.
On success, returns a calloc-ed int* of length n, all elements 0. The caller frees it. Return NULL for invalid/empty requests or allocation failure, as specified in the contract below.
zeros(4) -> {0, 0, 0, 0}
calloc (not malloc + manual zeroing). The caller frees the result.Drill: practice one contract before combining it with other skills.
n — the number of ints to allocate.
On success, returns a calloc-ed int* of length n, all elements 0. The caller frees it. Return NULL for invalid/empty requests or allocation failure, as specified in the contract below.
Return NULL for n <= 0 or unrepresentable byte size. Otherwise use calloc for n ints. Allocation failure returns NULL; caller owns and frees success.
#include <stdlib.h>
int *zeros(int n) {
/* TODO */
return NULL;
}
Using malloc without initialization or zeroing only the first element.
One element, all elements zero, invalid counts, and forced allocation failure.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.