Mail Archives: djgpp/1997/10/26/01:05:29
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
- Raw text -