pointers-memory · intermediate · ~16 min

Append with realloc

Grow a heap buffer and use realloc's returned pointer.

Challenge

Grow a heap array by one element with realloc and store a new value in the newly added slot, returning the pointer (which may have moved).

Task

Implement int *append(int *a, int n, int v) that reallocs the n-element heap array a to n+1 elements, writes v into the new last slot (index n), and returns the resulting pointer. No main — the grader calls it.

Input

a — an n-element malloc/realloc-ed array. n — its current length. v — the value to append.

Output

On success returns the (possibly relocated) pointer to the n+1-element array, with v at index n. On success the caller adopts and frees the returned pointer. On failure returns NULL and the caller retains the original allocation.

Example

a = {10, 20};  append(a, 2, 30)   ->   {10, 20, 30}

Rules

  • realloc may move the block, so always return and use its result.

Why this matters

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

Input format

a — an n-element malloc/realloc-ed array. n — its current length. v — the value to append.

Output format

On success returns the (possibly relocated) pointer to the n+1-element array, with v at index n. On success the caller adopts and frees the returned pointer. On failure returns NULL and the caller retains the original allocation.

Constraints

n >= 0; a is NULL only for n=0, otherwise an owned allocation of n ints. Reject invalid/unrepresentable growth with NULL. On nonzero realloc failure return NULL and leave the original allocation valid. On success caller adopts and frees the result.

Starter code

#include <stdlib.h>

int *append(int *a, int n, int v) {
    /* TODO */
    return a;
}

Common mistakes

Overwriting the only owner before checking realloc or writing at n+1 instead of n.

Edge cases to handle

Append to empty; preserve old elements; negative appended value; overflow check; allocation failure preserves the original.

Up next

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