14fee23f9Smrg /* Implement the strndup function.
2*b1e83836Smrg Copyright (C) 2005-2022 Free Software Foundation, Inc.
34fee23f9Smrg Written by Kaveh R. Ghazi <ghazi@caip.rutgers.edu>.
44fee23f9Smrg
54fee23f9Smrg This file is part of the libiberty library.
64fee23f9Smrg Libiberty is free software; you can redistribute it and/or
74fee23f9Smrg modify it under the terms of the GNU Library General Public
84fee23f9Smrg License as published by the Free Software Foundation; either
94fee23f9Smrg version 2 of the License, or (at your option) any later version.
104fee23f9Smrg
114fee23f9Smrg Libiberty is distributed in the hope that it will be useful,
124fee23f9Smrg but WITHOUT ANY WARRANTY; without even the implied warranty of
134fee23f9Smrg MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
144fee23f9Smrg Library General Public License for more details.
154fee23f9Smrg
164fee23f9Smrg You should have received a copy of the GNU Library General Public
174fee23f9Smrg License along with libiberty; see the file COPYING.LIB. If
184fee23f9Smrg not, write to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
194fee23f9Smrg Boston, MA 02110-1301, USA. */
204fee23f9Smrg
214fee23f9Smrg /*
224fee23f9Smrg
234fee23f9Smrg @deftypefn Extension char* strndup (const char *@var{s}, size_t @var{n})
244fee23f9Smrg
254fee23f9Smrg Returns a pointer to a copy of @var{s} with at most @var{n} characters
264fee23f9Smrg in memory obtained from @code{malloc}, or @code{NULL} if insufficient
274fee23f9Smrg memory was available. The result is always NUL terminated.
284fee23f9Smrg
294fee23f9Smrg @end deftypefn
304fee23f9Smrg
314fee23f9Smrg */
324fee23f9Smrg
334fee23f9Smrg #include "ansidecl.h"
344fee23f9Smrg #include <stddef.h>
354fee23f9Smrg
36b17d1066Smrg extern size_t strnlen (const char *s, size_t maxlen);
374fee23f9Smrg extern PTR malloc (size_t);
384fee23f9Smrg extern PTR memcpy (PTR, const PTR, size_t);
394fee23f9Smrg
404fee23f9Smrg char *
strndup(const char * s,size_t n)414fee23f9Smrg strndup (const char *s, size_t n)
424fee23f9Smrg {
434fee23f9Smrg char *result;
44b17d1066Smrg size_t len = strnlen (s, n);
454fee23f9Smrg
464fee23f9Smrg result = (char *) malloc (len + 1);
474fee23f9Smrg if (!result)
484fee23f9Smrg return 0;
494fee23f9Smrg
504fee23f9Smrg result[len] = '\0';
514fee23f9Smrg return (char *) memcpy (result, s, len);
524fee23f9Smrg }
53