\fBstrncpy\fP() は効率的でなく間違いを起こしやすいと考えるプログラマもいるだろう。 プログラマが \fIdest\fP の大きさが \fIsrc\fP
の長さよりも 大きいことを知っている (つまり、そのことをチェックするコードを 書いている) 場合は、 \fBstrcpy()\fP を使うことができる。
-One valid (and intended) use of \fBstrncpy\fP() is to copy a C string to a
-fixed\-length buffer while ensuring both that the buffer is not overflowed
-and that unused bytes in the target buffer are zeroed out (perhaps to
-prevent information leaks if the buffer is to be written to media or
-transmitted to another process via an interprocess communication technique).
+\fBstrncpy\fP() の正しい (かつ意図された) 用途は、 C 文字列の固定長バッファへのコピーを、 バッファがオーバーフローしないことと、
+宛先バッファの未使用バイトが 0 で埋められることの両方を保証しつつ行うことである。 (宛先バッファを 0 で埋めるのは、 たいていの場合、
+バッファを媒体に書き込んだり、別のプロセスにプロセス間通信を用いて送信したりした場合に情報洩れを防ぐためである)。
\fIsrc\fP の最初の \fIn\fP バイトに終端のヌルバイトがない場合、 \fBstrncpy\fP()
は \fIdest\fP に終端されていない文字列を生成する。以下のようにして
.fi
.in
.PP
-(Of course, the above technique ignores the fact that information contained
-in \fIsrc\fP is lost in the copying to \fIdest\fP.)
+(もちろん、上記の方法では、 \fIsrc\fP に入っている情報が \fIdest\fP へのコピー時に失われるという事実は無視している。)
いくつかのシステム (BSD、Solaris など) では以下の関数が提供されている。
.\" "strlcpy and strlcat - consistent, safe, string copy and concatenation"
.\" 1999 USENIX Annual Technical Conference
.\" https://lwn.net/Articles/506530/
-This function is similar to \fBstrncpy\fP(), but it copies at most \fIsize\-1\fP
-bytes to \fIdest\fP, always adds a terminating null byte, and does not pad the
-target with (further) null bytes. This function fixes some of the problems
-of \fBstrcpy\fP() and \fBstrncpy\fP(), but the caller must still handle the
-possibility of data loss if \fIsize\fP is too small. The return value of the
-function is the length of \fIsrc\fP, which allows truncation to be easily
-detected: if the return value is greater than or equal to \fIsize\fP,
-truncation occurred. If loss of data matters, the caller \fImust\fP either
-check the arguments before the call, or test the function return value.
-\fBstrlcpy\fP() is not present in glibc and is not standardized by POSIX, but
-is available on Linux via the \fIlibbsd\fP library.
+この関数は \fBstrncpy\fP() と同様だが、 最大でも \fIsize\-1\fP バイトしか \fIdest\fP にコピーをせず、 末尾への終端の NULL
+バイトの追加が必ず行われ、 宛先バッファ (の未使用部分) への NULL バイトの書き込みが行われない。 この関数では \fBstrcpy\fP() や
+\fBstrncpy\fP() の持つ問題のいくつかが修正されているが、 \fIsize\fP が小さすぎた場合にはデータが失われる問題には、
+依然として呼び出し側で対処する必要がある。 この関数の返り値は \fIsrc\fP の長さである。 これにより、
+末尾の切り詰めが行われたかを簡単に検出することができる。 返り値が \fIsize\fP 以上の場合には、 末尾の切り詰めが発生している。
+データロスが問題となる場合は、 呼び出し側で、 呼び出し前に引き数をチェックするか、 この関数の返り値を検査するかのいずれかをしなければならない。
+\fBstrlcpy\fP() は glibc には存在せず、 POSIX による標準化もされていないが、 Linux では \fIlibbsd\fP
+ライブラリ経由で利用できる。
.SH バグ
\fBstrcpy\fP() の受け側の文字列が十分な大きさでない場合、何が起こるかわからない。
固定長文字列を溢れさせるのは、マシンの制御を掌中に収めるために クラッカーが好んで使うテクニックである。