Strings In Depth16 / 18
Up next

strncpy safely

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

int main(void) {
    char dst[8];
    const char *src = "truncated string";
    strncpy(dst, src, sizeof dst - 1);
    dst[sizeof dst - 1] = '\0';
    printf("%s\n", dst);
    return 0;
}
What you're solving

copy at most n bytes, then terminate