strncpy(3)よりもstrlcpy(3)
strncpy(3)は、(本来文字数を指定するところに)ついうっかりバッファサイズを指定すると、不正なC文字列になってしまうので要注意です。やっぱりstrncpy(3)よりもstrlcpy(3)の方が、直感的なAPIでわかりやすいですね。でも*BSD以外でもstrlcpy(3)って使えたっけ?
以下、サンプルプログラム。
#include <stdio.h> #include <stdlib.h> #include <string.h> static void dump(const char *buf, size_t n) { size_t i; for (i = 0; i < n; i++) { putchar(buf[i]); } } int main(int argc, char *argv[]) { char buf[8]; strncpy(buf, "too long str", sizeof(buf)); /* 危険!! */ dump(buf, sizeof(buf)); /* => "too long" (not C-string.) */ strncpy(buf, "too long str", sizeof(buf) - 1); /* 面倒… */ buf[sizeof(buf) - 1] = '\0'; dump(buf, sizeof(buf)); /* => "too long\0" (C-string.) */ strlcpy(buf, "too long str", sizeof(buf)); dump(buf, sizeof(buf)); /* => "too long\0" (C-string.) */ return EXIT_SUCCESS; }