pointers-memory · intermediate · ~10 min
Bound a copy by the destination capacity.
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.
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.
dst — destination buffer. dstcap — its capacity in ints. src — source buffer. n — how many the caller wants to copy.
Returns the number of ints actually copied (min(n, dstcap)); dst is never written past dstcap.
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}
n > dstcap: copy only dstcap ints.n <= dstcap: copy all n.Drill: practice one contract before combining it with other skills.
dst — destination buffer. dstcap — its capacity in ints. src — source buffer. n — how many the caller wants to copy.
Returns the number of ints actually copied (min(n, dstcap)); dst is never written past dstcap.
n and dstcap are nonnegative; source has at least n readable ints and destination has dstcap writable ints. Buffers are live and do not overlap. Zero counts perform no access; NULL is allowed only for a zero-length corresponding buffer.
int safe_copy_n(int *dst, int dstcap, const int *src, int n) {
/* TODO */
return 0;
}
Copying n elements unconditionally; confusing bytes with ints; reading or writing one extra element.
Zero count/capacity; capacity smaller or larger than n; preserve destination suffix and neighboring sentinels.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.