basics · intermediate · ~15 min

Bounded concatenation

Append safely the way strlcat does.

Challenge

Append one string to another inside a fixed buffer, never overflowing — like strlcat.

Task

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.

Input

A buffer dst already holding a NUL-terminated string, its total capacity int dstsz, and a NUL-terminated src to append.

Output

Returns 0 if everything fit, or -1 if the result was truncated.

Example

dst = "foo" (cap 16);  safe_concat(dst, 16, "bar")     ->   0,   dst == "foobar"
dst = "foo" (cap 6);   safe_concat(dst, 6, "barbar")   ->   -1,  dst == "fooba"

Edge cases

  • When src does not fully fit, append as much as possible, NUL-terminate, and return -1.

Rules

  • Never write past dstsz-1 content bytes; always terminate.

Input format

A NUL-terminated dst, its capacity int dstsz, and a NUL-terminated src.

Output format

0 if all of src fit, otherwise -1 (truncated).

Constraints

Write at most dstsz-1 content bytes; always NUL-terminate.

Starter code

#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.