strncpy

Bill Poser poser at csli.Stanford.EDU
Tue Jan 23 13:17:20 AEST 1990


In article <48314938.f69e at phobos.UUCP> ellisond at phobos.UUCP (Dell Ellison) writes:
>                                                                      
>Actually, the reason why they are 'null-terminated strings' is because
>they are variable in length.  If you are using strncpy then you want an
>exact number of characters.

I think this reflects a confusion between variability in the size of
strings and variability in the size of string containers. (I don't
know if this is a standard term, but Bron & Dijkstra use it in
a recent SIGPLAN notices.) What strncpy is good for (or would be
good for if it null-terminated) is making sure that the copy does
not overflow the string container. The container may be (and usually is)
used for strings of variable length, and the strings copied may
be of variable length. At least in my experience, it is generally
not the case that one is trying to truncate the source string to
exactly N characters - rather, one is trying to copy as much of the
source string as will fit into the target container.

Note also that strncpy does not copy "an exact number of characters".
It copies up to N characters, stopping at the first null. In other
words, it observes the null-termination convention for the source
string, and does so for the target string if it isn't too long.
That's why it is a bastard function - it is designed to work with
the null-termination convention but does not guarantee closure.



More information about the Comp.lang.c mailing list