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