yohhoyの日記

技術的メモをしていきたい日記

長さゼロ on 文字列/メモリ操作関数

標準Cライブラリヘッダ string.h, wchar.h で提供される文字列/メモリ操作関数に対し、長さ 0 を指定した時の振る舞いについて。

操作対象とする文字列/メモリの “長さ” をとる関数において、該当引数に0を指定したときの振る舞いは下記の通り規定される。

char版 wchar_t版 効果/戻り値
strncpy(s1, s2, 0) wcsncpy(s1, s2, 0) 何もしない
strncat(s1, s2, 0) wcsncat(s1, s2, 0) 何もしない
strncmp(s1, s2, 0) wcsncmp(s1, s2, 0) 等値(0)を返す
strxfrm(s1, s2, 0) wcsxfrm(s1, s2, 0) 何もしない
memcpy(s1, s2, 0) wmemcpy(s1, s2, 0) 何もしない
memmove(s1, s2, 0) wmemmove(s1, s2, 0) 何もしない
memset(s, c, 0) wmemset(s, c, 0) 何もしない
memcmp(s1, s2, 0) wmemcmp(s1, s2, 0) 等値(0)を返す
memchr(s, c, 0) wmemchr(s, c, 0) 一致無し(NULL)を返す

C99(N1256) 7.12.1/p2より該当箇所を引用。7.24.4/p2も同一パラグラフ。

Where an argument declared as size_t n specifies the length of the array for a function, n can have the value zero on a call to that function. (snip) On such a call, a function that locates a character finds no occurrence, a function that compares two character sequences returns zero, and a function that copies characters copies zero characters.