pointers-memory · intermediate · ~14 min
Allocate and copy into heap memory.
Make an independent heap copy of an array, so the caller gets its own buffer to modify and free.
Implement int *dup_array(const int *a, int n) that returns a freshly malloc-ed copy of the first n elements of a. No main — the grader calls it and frees the result.
a — pointer to the source int array. n — the number of elements to copy.
On success, returns a new malloc-ed int* (distinct from a) holding a copy of the n elements. The caller frees it. Return NULL for invalid/empty requests or allocation failure, as specified in the contract below.
int src[] = {3, 1, 4, 1, 5};
dup_array(src, 5) -> {3, 1, 4, 1, 5} (a separate block, src != copy)
Drill: practice one contract before combining it with other skills.
a — pointer to the source int array. n — the number of elements to copy.
On success, returns a new malloc-ed int* (distinct from a) holding a copy of the n elements. The caller frees it. Return NULL for invalid/empty requests or allocation failure, as specified in the contract below.
For n <= 0, NULL source, or unrepresentable byte size return NULL. Otherwise read n live source ints and return a separately allocated copy. Failure returns NULL; input is never freed or modified; caller frees the copy.
#include <stdlib.h>
#include <string.h>
int *dup_array(const int *a, int n) {
/* TODO */
return NULL;
}
Returning the original array or copying n bytes instead of n ints.
One element, repeated and negative values, mutation of the copy leaves the source unchanged, empty/invalid request, allocation failure.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.