cybersecurity · intermediate · ~15 min
Append without overflowing.
Write a size-aware string append that respects the destination buffer's size — the safe replacement for strcat.
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.
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.Returns 0 if all of src fit, -1 if it was truncated. dst is always NUL-terminated.
dst="foo" (size 16) + "bar" -> 0, dst = "foobar"
dst="foo" (size 6) + "barbar" -> -1, dst = "fooba" (truncated)
dst unchanged.dst; never exceed dstsz - 1 total bytes; always NUL-terminate.A dst holding a NUL-terminated string, its size dstsz, and a NUL-terminated src.
0 if the append fit, -1 if truncated; dst always NUL-terminated.
Append without exceeding dstsz-1 total bytes; always NUL-terminate; report truncation.
#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.