basics · intermediate · ~15 min
Append safely the way strlcat does.
Append one string to another inside a fixed buffer, never overflowing — like strlcat.
Implement int safe_concat(char *dst, int dstsz, const char *src) that appends src onto the string already in dst. The result must fit in dstsz bytes including the terminating NUL, so write at most dstsz-1 content bytes and always NUL-terminate. Return 0 if all of src fit, or -1 if it had to be truncated. No main — the grader calls it.
A buffer dst already holding a NUL-terminated string, its total capacity int dstsz, and a NUL-terminated src to append.
Returns 0 if everything fit, or -1 if the result was truncated.
dst = "foo" (cap 16); safe_concat(dst, 16, "bar") -> 0, dst == "foobar"
dst = "foo" (cap 6); safe_concat(dst, 6, "barbar") -> -1, dst == "fooba"
src does not fully fit, append as much as possible, NUL-terminate, and return -1.dstsz-1 content bytes; always terminate.A NUL-terminated dst, its capacity int dstsz, and a NUL-terminated src.
0 if all of src fit, otherwise -1 (truncated).
Write at most dstsz-1 content bytes; always NUL-terminate.
#include <string.h>
int safe_concat(char *dst, int dstsz, const char *src) {
/* TODO */
return -1;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.