strncpy

Bill Poser poser at csli.Stanford.EDU
Sun Dec 24 07:43:16 AEST 1989


In response to my query about why strncpy does not null terminate
Dr. T. Andrews <cdis-1!tanner at uunet.UU.NET> writes:

>Your brain is probably broken.  The reason that strncpy() does
>not null terminate is so that the supplied buffer is not over-run.
>If it were to do as you suggest, then it would be of no value as the
>data following the destination might be randomly clobbered.
>Alternatively, truncating the source one byte too soon would be
>unhelpful: you would lose data for which you had space.

(Since direct mail seems to be problematic, I respond here.)
One can't help but be overwhelmed by this charming, witty, and insightful
response. Only a genius like Dr. Tanner would think of not overflowing
the buffer. The "waste" of the terminating null is REQUIRED so long
as one conforms to the usual, null-terminated representation of strings
in C. All other representations of arbitrary length strings require
similar overhead, e.g. a character count in the descriptor. The
case in which the terminating null or character count can be dispensed
with is that of strings with a known maximum length, as in pre-Berkeley
style directory entries, for which I have been told strncpy was designed.
In sum, as part of the standard C string implementation, strncpy is
deviant. It was actually designed to deal with a different representation
of strings, and doesn't quite form a coherent part of the standard string
library.



More information about the Comp.lang.c mailing list