cybersecurity · intermediate · ~15 min

strlcat-style append

Append without overflowing.

Challenge

Write a size-aware string append that respects the destination buffer's size — the safe replacement for strcat.

Task

Implement int safe_cat(char *dst, int dstsz, const char *src) that appends src onto the NUL-terminated string already in dst without ever exceeding dstsz - 1 total bytes, always NUL-terminating. Return 0 if the whole append fit, -1 if it was truncated.

Input

  • dst: a buffer holding a NUL-terminated string, total size dstsz.
  • dstsz: the size of dst in bytes.
  • src: a NUL-terminated string to append.

Output

Returns 0 if all of src fit, -1 if it was truncated. dst is always NUL-terminated.

Example

dst="foo" (size 16) + "bar"      ->   0,  dst = "foobar"
dst="foo" (size 6)  + "barbar"   ->   -1, dst = "fooba"   (truncated)

Edge cases

  • Appending an empty string: returns 0, dst unchanged.
  • The combined length exactly filling the buffer: return 0.

Rules

  • Start at the current end of dst; never exceed dstsz - 1 total bytes; always NUL-terminate.

Input format

A dst holding a NUL-terminated string, its size dstsz, and a NUL-terminated src.

Output format

0 if the append fit, -1 if truncated; dst always NUL-terminated.

Constraints

Append without exceeding dstsz-1 total bytes; always NUL-terminate; report truncation.

Starter code

#include <string.h>

int safe_cat(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.