Copying a Short String into a Large Buffer: strncpy vs memcpy

Question 44 / 51 Correct so far: 0 (0 answered)

Snippet A

Strncpy Copy

NOINLINE void copyString(char* buf, const char* src) {
    strncpy(buf, src, kBufSize);
}

copyString(dst, kSrc);
Snippet B

Memcpy Copy

NOINLINE void copyString(char* buf, const char* src, std::size_t len) {
    memcpy(buf, src, len + 1);  // +1 copies the null terminator
}

copyString(dst, kSrc, kSrcLen);
Shared test data (shared-setup)
constexpr std::size_t kBufSize = 4096;
static const char kSrc[] = "hello, world!";
constexpr std::size_t kSrcLen = sizeof(kSrc) - 1;  // excludes null terminator

static char dst[kBufSize];

Which snippet is faster?

Select the correct answer(s)