From: Erik Max Francis Newsgroups: comp.os.msdos.djgpp Subject: Re: strncpy question Date: Sat, 25 Oct 1997 13:46:54 -0700 Organization: Alcyone Systems Lines: 35 Message-ID: <34525ABE.54074B5A@alcyone.com> References: <199710240221 DOT MAA29326 AT rabble DOT uow DOT edu DOT au> NNTP-Posting-Host: newton.alcyone.com Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Precedence: bulk Brett Porter wrote: > It started to overwrite other memory. > I realise what I had done here was bad coding, and I've fixed it up, > but I > was curious what was going on here. IS the definition of strncpy in > DJGPP to > zero out up to the limit specified, or does it stop at the NULL > character? I > thought it was the latter but this example would seem to indicate > otherwise. > > No urgency in replying, I'm just curious strncpy, contrary to what it might sound like from the name (namely that it begins with str) does _not_ always give you a NUL-terminated, possibly truncated, string. strncpy (and its counterpart, strncat) is intended for padding strings into fixed-size arrays. The remainder of the string is NUL padded. ANSI C even has a footnote which mentions this (7.11.2.4, footnote 134): Thus, if there is no null character in the first n characters of the [string to be copied], the result will not be null-terminated. Basically, don't use strncpy or strncat except in cases where you're trying to fill a fixed-sized buffer, and do not care whether or not the result is NUL-terminated (but _do_ care if it is NUL-padded). -- Erik Max Francis, &tSftDotIotE / mailto:max AT alcyone DOT com Alcyone Systems / http://www.alcyone.com/max/ San Jose, California, United States / icbm://+37.20.07/-121.53.38 \ "After each war there is a little / less democracy to save." / Brooks Atkinson