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