pointers-memory · intermediate · ~16 min
Grow a heap buffer and use realloc's returned pointer.
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).
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.
a — an n-element malloc/realloc-ed array. n — its current length. v — the value to append.
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.
a = {10, 20}; append(a, 2, 30) -> {10, 20, 30}
realloc may move the block, so always return and use its result.Drill: practice one contract before combining it with other skills.
a — an n-element malloc/realloc-ed array. n — its current length. v — the value to append.
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.
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.
#include <stdlib.h>
int *append(int *a, int n, int v) {
/* TODO */
return a;
}
Overwriting the only owner before checking realloc or writing at n+1 instead of n.
Append to empty; preserve old elements; negative appended value; overflow check; allocation failure preserves the original.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.