pointers-memory · intermediate · ~15 min

Capacity-checked copy

Bound a copy by the destination capacity.

Challenge

Copy ints into a destination buffer without ever overrunning it: copy at most as many as the destination can hold, and report how many you actually copied.

Task

Implement int safe_copy_n(int *dst, int dstcap, const int *src, int n) that copies min(n, dstcap) ints from src to dst and returns that count. No main — the grader calls it.

Input

dst — destination buffer. dstcap — its capacity in ints. src — source buffer. n — how many the caller wants to copy.

Output

Returns the number of ints actually copied (min(n, dstcap)); dst is never written past dstcap.

Example

src = {1,2,3,4}, dst capacity 2:  safe_copy_n(dst, 2, src, 4)   ->   2, dst == {1, 2}
src = {1,2,3,4}, dst capacity 8:  safe_copy_n(dst, 8, src, 4)   ->   4, dst[0..3] == {1,2,3,4}

Edge cases

  • n > dstcap: copy only dstcap ints.
  • n <= dstcap: copy all n.

Input format

dst/dstcap — destination and its capacity; src/n — source and requested count.

Output format

The number of ints copied (min(n, dstcap)); dst is never overrun.

Constraints

Never write past dstcap ints into dst.

Starter code

int safe_copy_n(int *dst, int dstcap, const int *src, int n) {
    /* TODO */
    return 0;
}

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