xref: /dflybsd-src/contrib/binutils-2.27/libiberty/xstrndup.c (revision e656dc90e3d65d744d534af2f5ea88cf8101ebcf)
1*a9fa9459Szrj /* Implement the xstrndup function.
2*a9fa9459Szrj    Copyright (C) 2005 Free Software Foundation, Inc.
3*a9fa9459Szrj    Written by Kaveh R. Ghazi <ghazi@caip.rutgers.edu>.
4*a9fa9459Szrj 
5*a9fa9459Szrj This file is part of the libiberty library.
6*a9fa9459Szrj Libiberty is free software; you can redistribute it and/or
7*a9fa9459Szrj modify it under the terms of the GNU Library General Public
8*a9fa9459Szrj License as published by the Free Software Foundation; either
9*a9fa9459Szrj version 2 of the License, or (at your option) any later version.
10*a9fa9459Szrj 
11*a9fa9459Szrj Libiberty is distributed in the hope that it will be useful,
12*a9fa9459Szrj but WITHOUT ANY WARRANTY; without even the implied warranty of
13*a9fa9459Szrj MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14*a9fa9459Szrj Library General Public License for more details.
15*a9fa9459Szrj 
16*a9fa9459Szrj You should have received a copy of the GNU Library General Public
17*a9fa9459Szrj License along with libiberty; see the file COPYING.LIB.  If
18*a9fa9459Szrj not, write to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
19*a9fa9459Szrj Boston, MA 02110-1301, USA.  */
20*a9fa9459Szrj 
21*a9fa9459Szrj /*
22*a9fa9459Szrj 
23*a9fa9459Szrj @deftypefn Replacement char* xstrndup (const char *@var{s}, size_t @var{n})
24*a9fa9459Szrj 
25*a9fa9459Szrj Returns a pointer to a copy of @var{s} with at most @var{n} characters
26*a9fa9459Szrj without fail, using @code{xmalloc} to obtain memory.  The result is
27*a9fa9459Szrj always NUL terminated.
28*a9fa9459Szrj 
29*a9fa9459Szrj @end deftypefn
30*a9fa9459Szrj 
31*a9fa9459Szrj */
32*a9fa9459Szrj 
33*a9fa9459Szrj #ifdef HAVE_CONFIG_H
34*a9fa9459Szrj #include "config.h"
35*a9fa9459Szrj #endif
36*a9fa9459Szrj #include <sys/types.h>
37*a9fa9459Szrj #ifdef HAVE_STRING_H
38*a9fa9459Szrj #include <string.h>
39*a9fa9459Szrj #else
40*a9fa9459Szrj # ifdef HAVE_STRINGS_H
41*a9fa9459Szrj #  include <strings.h>
42*a9fa9459Szrj # endif
43*a9fa9459Szrj #endif
44*a9fa9459Szrj #include "ansidecl.h"
45*a9fa9459Szrj #include "libiberty.h"
46*a9fa9459Szrj 
47*a9fa9459Szrj char *
xstrndup(const char * s,size_t n)48*a9fa9459Szrj xstrndup (const char *s, size_t n)
49*a9fa9459Szrj {
50*a9fa9459Szrj   char *result;
51*a9fa9459Szrj   size_t len = strlen (s);
52*a9fa9459Szrj 
53*a9fa9459Szrj   if (n < len)
54*a9fa9459Szrj     len = n;
55*a9fa9459Szrj 
56*a9fa9459Szrj   result = XNEWVEC (char, len + 1);
57*a9fa9459Szrj 
58*a9fa9459Szrj   result[len] = '\0';
59*a9fa9459Szrj   return (char *) memcpy (result, s, len);
60*a9fa9459Szrj }
61