typestar

Copying strings in C

strcpy trusts you completely; strncpy does not always terminate. Know both traps.

#include <string.h>

void copy_bounded(char *dst, size_t cap, const char *src) {
    if (cap == 0) {
        return;
    }
    strncpy(dst, src, cap - 1);
    dst[cap - 1] = '\0';
}

size_t copy_reporting(char *dst, size_t cap, const char *src) {
    size_t needed = strlen(src);
    if (cap > 0) {
        size_t fits = (needed < cap - 1) ? needed : cap - 1;
        memcpy(dst, src, fits);
        dst[fits] = '\0';
    }
    return needed;
}

How it works

  1. strcpy writes until the source's NUL, however big the target is.
  2. strncpy stops at n bytes and may leave no terminator.
  3. Writing the terminator yourself is the habit that saves you.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
380
Tokens
124
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 78 seconds.

Type this snippet

Step 1 of 4 in Copying & building, step 1 of 13 in Strings & text.

Next →