116dce513Schristos /* Implement the xstrndup function.
2*e992f068Schristos Copyright (C) 2005-2022 Free Software Foundation, Inc.
316dce513Schristos Written by Kaveh R. Ghazi <ghazi@caip.rutgers.edu>.
416dce513Schristos
516dce513Schristos This file is part of the libiberty library.
616dce513Schristos Libiberty is free software; you can redistribute it and/or
716dce513Schristos modify it under the terms of the GNU Library General Public
816dce513Schristos License as published by the Free Software Foundation; either
916dce513Schristos version 2 of the License, or (at your option) any later version.
1016dce513Schristos
1116dce513Schristos Libiberty is distributed in the hope that it will be useful,
1216dce513Schristos but WITHOUT ANY WARRANTY; without even the implied warranty of
1316dce513Schristos MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
1416dce513Schristos Library General Public License for more details.
1516dce513Schristos
1616dce513Schristos You should have received a copy of the GNU Library General Public
1716dce513Schristos License along with libiberty; see the file COPYING.LIB. If
1816dce513Schristos not, write to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
1916dce513Schristos Boston, MA 02110-1301, USA. */
2016dce513Schristos
2116dce513Schristos /*
2216dce513Schristos
2316dce513Schristos @deftypefn Replacement char* xstrndup (const char *@var{s}, size_t @var{n})
2416dce513Schristos
2516dce513Schristos Returns a pointer to a copy of @var{s} with at most @var{n} characters
2616dce513Schristos without fail, using @code{xmalloc} to obtain memory. The result is
2716dce513Schristos always NUL terminated.
2816dce513Schristos
2916dce513Schristos @end deftypefn
3016dce513Schristos
3116dce513Schristos */
3216dce513Schristos
3316dce513Schristos #ifdef HAVE_CONFIG_H
3416dce513Schristos #include "config.h"
3516dce513Schristos #endif
3616dce513Schristos #include <sys/types.h>
3716dce513Schristos #ifdef HAVE_STRING_H
3816dce513Schristos #include <string.h>
3916dce513Schristos #else
4016dce513Schristos # ifdef HAVE_STRINGS_H
4116dce513Schristos # include <strings.h>
4216dce513Schristos # endif
4316dce513Schristos #endif
4416dce513Schristos #include "ansidecl.h"
4516dce513Schristos #include "libiberty.h"
4616dce513Schristos
4716dce513Schristos char *
xstrndup(const char * s,size_t n)4816dce513Schristos xstrndup (const char *s, size_t n)
4916dce513Schristos {
5016dce513Schristos char *result;
51ede78133Schristos size_t len = strnlen (s, n);
5216dce513Schristos
5316dce513Schristos result = XNEWVEC (char, len + 1);
5416dce513Schristos
5516dce513Schristos result[len] = '\0';
5616dce513Schristos return (char *) memcpy (result, s, len);
5716dce513Schristos }
58