pointers-memory · intermediate · ~8 min

Zero-initialised allocation

Use calloc for zeroed memory.

Challenge

Allocate a zero-initialised int array using calloc, which both reserves and zeroes the memory in one call.

Task

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.

Input

n — the number of ints to allocate.

Output

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.

Example

zeros(4)   ->   {0, 0, 0, 0}

Rules

  • Use calloc (not malloc + manual zeroing). The caller frees the result.

Why this matters

Drill: practice one contract before combining it with other skills.

Input format

n — the number of ints to allocate.

Output format

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.

Constraints

Return NULL for n <= 0 or unrepresentable byte size. Otherwise use calloc for n ints. Allocation failure returns NULL; caller owns and frees success.

Starter code

#include <stdlib.h>

int *zeros(int n) {
    /* TODO */
    return NULL;
}

Common mistakes

Using malloc without initialization or zeroing only the first element.

Edge cases to handle

One element, all elements zero, invalid counts, and forced allocation failure.

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.