pointers-memory · intermediate · ~16 min

Deep-copy an int array

Allocate + copy. The motivating concept of "deep" vs "shallow" copy.

Challenge

Make an independent heap copy of an int array, so mutating the copy never affects the original.

Task

Implement int *copy_ints(const int *src, size_t n) that returns a freshly allocated array holding the same n ints as src. No main — the grader calls it.

Input

  • src: pointer to the source array of int.
  • n: the number of elements. May be 0.

Output

A pointer to a new malloc-ed array with the same contents as src. The caller frees it. If n == 0 you may return NULL.

Example

copy_ints({4,5,6,7}, 4)   ->   new array {4,5,6,7}, independent of the source

Edge cases

  • n = 0: you may return NULL.
  • Mutating the returned array must NOT change src (this is a deep copy).
  • Return NULL if allocation fails.

Rules

  • Allocate new storage and copy; do not return src itself.

Why this matters

Transfer exercise: apply the lesson to a complete function contract.

Input format

  • src: pointer to the source array of int.
  • n: the number of elements. May be 0.

Output format

A pointer to a new malloc-ed array with the same contents as src. The caller frees it. If n == 0 you may return NULL.

Constraints

n=0 returns NULL; otherwise src is a non-NULL live array of n ints. Reject NULL source, size overflow, or allocation failure with NULL. Caller owns copy; input is borrowed.

Starter code

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

int *copy_ints(const int *src, size_t n) {
    /* TODO */
    return NULL;
}

Common mistakes

Returning src, forgetting size overflow, or copying only n bytes.

Edge cases to handle

Empty array; independent storage; unchanged source; allocation failure.

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