Path: utzoo!utgpu!jarvis.csri.toronto.edu!clyde.concordia.ca!uunet!wuarchive!decwrl!shelby!csli!poser From: poser@csli.Stanford.EDU (Bill Poser) Newsgroups: comp.lang.c Subject: strncpy Keywords: strncpy null termination Message-ID: <11527@csli.Stanford.EDU> Date: 23 Dec 89 20:43:16 GMT Sender: poser@csli.Stanford.EDU (Bill Poser) Organization: Center for the Study of Language and Information, Stanford U. Lines: 24 In response to my query about why strncpy does not null terminate Dr. T. Andrews 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.