truncating string copy

The majority of our calls to strncpy are in the form
  (void) strncpy(dst, src, n);
  dst[n] = '\0';
so add a new routine, copynchars, which does that.  A few calls care
about strncpy's return value and at least one relies on it only copying a
substring without also terminating the output, but most don't care about
either and none seem to care that `n' ought to have type size_t instead of
int.  The new routine matches our usage better, but I haven't gone through
to change the existing strncpy calls.
This commit is contained in:
nethack.rankin
2007-03-06 03:00:05 +00:00
parent 2adc83e145
commit 5a874440a0
3 changed files with 21 additions and 4 deletions

View File

@@ -1,4 +1,4 @@
/* SCCS Id: @(#)hacklib.c 3.5 2004/04/11 */
/* SCCS Id: @(#)hacklib.c 3.5 2007/03/05 */
/* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */
/* Copyright (c) Robert Patrick Rankin, 1991 */
/* NetHack may be freely redistributed. See license for details. */
@@ -19,6 +19,7 @@ NetHack, except that rounddiv may call panic().
char * mungspaces (char *)
char * eos (char *)
char * strkitten (char *,char)
void copynchars (char *,const char *,int)
char * s_suffix (const char *)
char * xcrypt (const char *, char *)
boolean onlyspace (const char *)
@@ -139,6 +140,22 @@ strkitten(s, c) /* append a character to a string (in place) */
return s;
}
void
copynchars(dst, src, n) /* truncating string copy */
char *dst;
const char *src;
int n;
{
/* copies at most n characters, stopping sooner if terminator reached;
treats newline as input terminator; unlike strncpy, always supplies
'\0' terminator so dst must be able to hold at least n+1 characters */
while (n > 0 && *src != '\0' && *src != '\n') {
*dst++ = *src++;
--n;
}
*dst = '\0';
}
char *
s_suffix(s) /* return a name converted to possessive */
const char *s;