198b9484cSchristos /* Implement the xstrndup function. 2*5173eb0aSchristos Copyright (C) 2005-2024 Free Software Foundation, Inc. 398b9484cSchristos Written by Kaveh R. Ghazi <ghazi@caip.rutgers.edu>. 498b9484cSchristos 598b9484cSchristos This file is part of the libiberty library. 698b9484cSchristos Libiberty is free software; you can redistribute it and/or 798b9484cSchristos modify it under the terms of the GNU Library General Public 898b9484cSchristos License as published by the Free Software Foundation; either 998b9484cSchristos version 2 of the License, or (at your option) any later version. 1098b9484cSchristos 1198b9484cSchristos Libiberty is distributed in the hope that it will be useful, 1298b9484cSchristos but WITHOUT ANY WARRANTY; without even the implied warranty of 1398b9484cSchristos MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 1498b9484cSchristos Library General Public License for more details. 1598b9484cSchristos 1698b9484cSchristos You should have received a copy of the GNU Library General Public 1798b9484cSchristos License along with libiberty; see the file COPYING.LIB. If 1898b9484cSchristos not, write to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor, 1998b9484cSchristos Boston, MA 02110-1301, USA. */ 2098b9484cSchristos 2198b9484cSchristos /* 2298b9484cSchristos 2398b9484cSchristos @deftypefn Replacement char* xstrndup (const char *@var{s}, size_t @var{n}) 2498b9484cSchristos 2598b9484cSchristos Returns a pointer to a copy of @var{s} with at most @var{n} characters 2698b9484cSchristos without fail, using @code{xmalloc} to obtain memory. The result is 2798b9484cSchristos always NUL terminated. 2898b9484cSchristos 2998b9484cSchristos @end deftypefn 3098b9484cSchristos 3198b9484cSchristos */ 3298b9484cSchristos 3398b9484cSchristos #ifdef HAVE_CONFIG_H 3498b9484cSchristos #include "config.h" 3598b9484cSchristos #endif 3698b9484cSchristos #include <sys/types.h> 3798b9484cSchristos #ifdef HAVE_STRING_H 3898b9484cSchristos #include <string.h> 3998b9484cSchristos #else 4098b9484cSchristos # ifdef HAVE_STRINGS_H 4198b9484cSchristos # include <strings.h> 4298b9484cSchristos # endif 4398b9484cSchristos #endif 4498b9484cSchristos #include "ansidecl.h" 4598b9484cSchristos #include "libiberty.h" 4698b9484cSchristos 4798b9484cSchristos char * 4898b9484cSchristos xstrndup (const char *s, size_t n) 4998b9484cSchristos { 5098b9484cSchristos char *result; 51796c32c9Schristos size_t len = strnlen (s, n); 5298b9484cSchristos 5398b9484cSchristos result = XNEWVEC (char, len + 1); 5498b9484cSchristos 5598b9484cSchristos result[len] = '\0'; 5698b9484cSchristos return (char *) memcpy (result, s, len); 5798b9484cSchristos } 58