C Programming Fundamentals: Worked Examples
Work through each trace before reading the explanation. Then solve the transfer task without the page open.
Example 1: Capacity includes the terminator
A buffer of four char elements holds at most three input bytes plus the terminating zero when used as a C string. Copying four payload bytes and then writing a terminator at index 4 exceeds its bounds.
The contract should include destination capacity and a defined failure or truncation policy. “The destination pointer is non-null” is insufficient. Test lengths 0,2,3,4 against capacity 4; distinguish bytes accepted from storage required.
Example 2: End-of-file must remain distinguishable
A character-reading function returns int so it can represent every unsigned-char value and a distinct EOF result. Saving its return value into char before testing EOF can lose that distinction.
Use an int variable for the returned value, compare it with EOF, and only then process the valid character value. Otherwise behavior can depend on whether plain char is signed and on the input bytes. A text-only happy-path test may miss this representation error.
Transfer and self-check
How much storage holds five payload bytes as a terminated C string? Check: at least six char elements. Explain why this is a byte-storage answer, not a Unicode character-count rule.
Evidence to keep
Save your first attempt, corrected reasoning, and transfer result as checkpoint evidence. A matching final answer without an explanation is insufficient. Continue with the guided lab and use the reading guide to repair a specific gap.