pointers-memory · intermediate · ~14 min

Duplicate an array

Allocate and copy into heap memory.

Challenge

Make an independent heap copy of an array, so the caller gets its own buffer to modify and free.

Task

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.

Input

a — pointer to the source int array. n — the number of elements to copy.

Output

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.

Example

int src[] = {3, 1, 4, 1, 5};
dup_array(src, 5)   ->   {3, 1, 4, 1, 5}   (a separate block, src != copy)

Rules

  • The copy is a separate heap block; the caller frees it.

Why this matters

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

Input format

a — pointer to the source int array. n — the number of elements to copy.

Output format

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.

Constraints

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.

Starter code

#include <stdlib.h>
#include <string.h>

int *dup_array(const int *a, int n) {
    /* TODO */
    return NULL;
}

Common mistakes

Returning the original array or copying n bytes instead of n ints.

Edge cases to handle

One element, repeated and negative values, mutation of the copy leaves the source unchanged, empty/invalid request, allocation failure.

Up next

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