pointers-memory · intermediate · ~16 min
Allocate + copy. The motivating concept of "deep" vs "shallow" copy.
Make an independent heap copy of an int array, so mutating the copy never affects the original.
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.
src: pointer to the source array of int.n: the number of elements. May be 0.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.
copy_ints({4,5,6,7}, 4) -> new array {4,5,6,7}, independent of the source
n = 0: you may return NULL.src (this is a deep copy).NULL if allocation fails.src itself.Transfer exercise: apply the lesson to a complete function contract.
src: pointer to the source array of int.n: the number of elements. May be 0.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.
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.
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
int *copy_ints(const int *src, size_t n) {
/* TODO */
return NULL;
}
Returning src, forgetting size overflow, or copying only n bytes.
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.