Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!cs.utexas.edu!swrinde!zaphod.mps.ohio-state.edu!think!mintaka!snorkelwacker!paperboy!skeptic!meissner From: meissner@skeptic.osf.org (Michael Meissner) Newsgroups: comp.lang.c Subject: Re: strncpy Keywords: strncpy null termination Message-ID: <2222@paperboy.OSF.ORG> Date: 21 Dec 89 23:07:32 GMT References: <11509@csli.Stanford.EDU> Sender: news@OSF.ORG Reply-To: meissner@skeptic.osf.org (Michael Meissner) Organization: Open Software Foundation Lines: 49 In article <11509@csli.Stanford.EDU> poser@csli.Stanford.EDU (Bill Poser) writes: | Why is it that strncpy(3) does not null terminate |the string if the length of the source string is greater than |or equal to the length of the target buffer? Strncpy was created to deal with the pre-Berkeley UNIX file system, whose directory entry took up exactly 16 bytes: 2 bytes for the inode # of the file 14 bytes for the filename If the filename was exactly 14 characters, no null would be used (>14 characters would be truncated). This fact blew away some early attempts at building a readdir function, which is spec'ed to return a null terminated name. I believe, that the kernel would compare all 14 bytes to see if they were equal when doing the namei (name to inode) transformation, which is why strncpy is required to zero out all bytes, if the string is less than n bytes. In addition to limiting names to the wierd 14 character limit, I think that the above scheme also is responsible for breaking large disks into tiny pieces, since each disk piece could not have more than 65K inodes. I suspect that many UNIX systems will shortly be in for the same shock, since 1GB disks are now appearring, and we should soon hit the limit for 32-bit inode numbers. Even if the system can support a multiple GB disk, single files will probably still be limited to 2GB, unless your system supports 64-bit longs (or uses the long long kludge + prototypes all the time). | I cannot think of |any circumstances in which this behaviour is desirable, and |always end up null terminating it myself. The only case in |which a non-null-terminated string might be useful would be |one in which a different representation for strings (e.g. |descriptors) is used, in which case the use of str(n)cpy would |not be appropriate anyhow. It seems to me that the behaviour |of strncpy provides: (a) a source of bugs for people who don't |bother to arrange null-termination themselves; (b) extra work for |those who take care; or, (c) just enough of a pain to be unsafe and |use strcpy(3). | | So I claim that strncpy is mis-designed and should |null-terminate. Any comments? | | Bill