Write copy_string that copies source into destination when capacity is non-zero, always terminates the destination, and reports failure if the source will not fit.
Requirements
Accept null source/destination safely
Leave destination terminated on success
Do not use unchecked strcpy
Example
Input
cat, capacity 4
Expected output
1
Show a hint
Write down the input contract and the failure cases before coding.
local runtime
RUNTIME OUTPUT
Use your C runtime locally, then compare with solution.c.
Use your local runtime, then review the reference solution
LEARN FROM THE SOLUTION
Why the solution works.
The destination needs room for every source byte plus the terminator, so the fit check is length < capacity. Copying through index <= length deliberately includes '\0'; writing an empty string on failure leaves a predictable destination state.
What this exercise teaches
Buffer capacity
Size-bounded copying
API return contracts
A PRACTICAL PLAN
Work through Copy a string with a capacity contract with intent.
Translate the contract.Turn the requirements into a short checklist before editing your-solution.c.
Use the example as evidence.Predict the result for the supplied input, then add one boundary case such as an empty value, a limit, or unexpected input.
Review the implementation.Compare your choices against solution.c only after a real attempt.
EXERCISE FAQ
Before you move on.
What does “Copy a string with a capacity contract” teach?
This intermediate C exercise focuses on Buffer capacity, Size-bounded copying, API return contracts. Its requirements define the exact behavior to implement before you write code.
How should I validate this C solution?
Start with the displayed example input and expected output, then test a boundary case suggested by the requirements. Write and compile the starter in your local C environment, exercise the example and edge cases, then compare your approach with solution.c.
When should I open the reference solution?
Attempt Copy a string with a capacity contract first. Then open the read-only solution file to compare the contract, edge-case handling, and implementation choices—not simply to copy the final code.