1 /****************************************************************
2 Copyright 1990 by AT&T Bell Laboratories and Bellcore.
4 Permission to use, copy, modify, and distribute this software
5 and its documentation for any purpose and without fee is hereby
6 granted, provided that the above copyright notice appear in all
7 copies and that both that the copyright notice and this
8 permission notice and warranty disclaimer appear in supporting
9 documentation, and that the names of AT&T Bell Laboratories or
10 Bellcore or any of their entities not be used in advertising or
11 publicity pertaining to distribution of the software without
12 specific, written prior permission.
14 AT&T and Bellcore disclaim all warranties with regard to this
15 software, including all implied warranties of merchantability
16 and fitness. In no event shall AT&T or Bellcore be liable for
17 any special, indirect or consequential damages or any damages
18 whatsoever resulting from loss of use, data or profits, whether
19 in an action of contract, negligence or other tortious action,
20 arising out of or in connection with the use or performance of
22 ****************************************************************/
26 Copies at most max_length characters, stopping at the first \0
27 character in source. The algorithm correctly handles overlapping
36 char *safe_strncpy (dest, source, max_length)
41 /* There are several conditions to be considered in determining buffer
44 Buffer Overlap? Picture Direction In Which To Copy
45 ---------------------------------------------------------------------------
46 1. dest == source | dest/src | no copy necessary
49 2. tail of dest against | dest | | src | left to right
50 head of source ---------===--------
52 3. head of dest against | src | | dest | right to left
53 tail of source --------===---------
55 4. no overlap |src| |dest| or |dest| |src| either direction
56 ----- ------ ------ -----
59 register char *ret_val = dest;
60 register int real_length;
62 if (source == NULL || dest == NULL)
65 /* Compute the actual length of the text to be copied */
67 for (real_length = 0; real_length < max_length && source[real_length];
70 /* Account for condition 3, dest head v. source tail */
72 if (source + real_length >= dest && source < dest)
73 for (; real_length >= 0; real_length--)
74 dest[real_length] = source[real_length];
76 /* Account for conditions 2 and 4, dest tail v. source head or no overlap */
78 else if (source != dest)
79 for (; real_length >= 0; real_length--)
82 /* Implicitly handle condition 1, by not performing the copy */