</>EmbeddedInterview
← All problems · Pointers & Strings

Safe String Copy (strlcpy)

Easy

Implement size_t my_strlcpy(char *dst, const char *src, size_t size):

  • Copy at most size - 1 characters and always NUL-terminate dst when size > 0.
  • Return the length of src (so the caller can detect truncation when the return value is >= size).
  • Do not use any library string functions.

Write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.

Copy while there is room, then keep counting the rest of src without copying to compute the return value.

#include <stdio.h>
#include <string.h>
#include <stddef.h>

size_t my_strlcpy(char *dst, const char *src, size_t size)
{
    const char *s = src;
    if (size) {
        while (--size && *s)
            *dst++ = *s++;
        *dst = '\0';
    }
    while (*s) s++;            /* count the remainder */
    return (size_t)(s - src);
}

strncpy is not a safe replacement for strcpy: it does not terminate the destination when the source is too long, and it zero-pads the whole buffer, which wastes time. strlcpy semantics (BSD, and now in glibc 2.38 and POSIX 2024) fix both. Returning the full source length lets callers write if (my_strlcpy(d, s, n) >= n) /* truncated */.

Edge cases interviewers check: size == 0, empty source, and exact-fit strings.

solution.c
OutputPress Run to compile and test your code.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
    char b[8];
    CHECK(my_strlcpy(b, "hi", sizeof b) == 2 && strcmp(b, "hi") == 0);
    CHECK(my_strlcpy(b, "overflowing", sizeof b) == 11 && strcmp(b, "overflo") == 0);
    CHECK(my_strlcpy(b, "", sizeof b) == 0 && b[0] == '\0');
    b[0] = 'X';
    CHECK(my_strlcpy(b, "abc", 0) == 3 && b[0] == 'X');   /* size 0: write nothing */
    puts(fails ? "Some tests failed" : "All tests passed");
    return fails != 0;
}