xref: /netbsd-src/external/gpl3/gdb/dist/libiberty/strndup.c (revision 7e120ff03ede3fe64e2c8620c01465d528502ddb)
198b9484cSchristos /* Implement the strndup function.
2*7e120ff0Schristos    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 Extension char* strndup (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 in memory obtained from @code{malloc}, or @code{NULL} if insufficient
2798b9484cSchristos memory was available.  The result is always NUL terminated.
2898b9484cSchristos 
2998b9484cSchristos @end deftypefn
3098b9484cSchristos 
3198b9484cSchristos */
3298b9484cSchristos 
3398b9484cSchristos #include "ansidecl.h"
3498b9484cSchristos #include <stddef.h>
3598b9484cSchristos 
36796c32c9Schristos extern size_t	strnlen (const char *s, size_t maxlen);
374b169a6bSchristos extern void *malloc (size_t);
384b169a6bSchristos extern void *memcpy (void *, const void *, size_t);
3998b9484cSchristos 
4098b9484cSchristos char *
4198b9484cSchristos strndup (const char *s, size_t n)
4298b9484cSchristos {
4398b9484cSchristos   char *result;
44796c32c9Schristos   size_t len = strnlen (s, n);
4598b9484cSchristos 
4698b9484cSchristos   result = (char *) malloc (len + 1);
4798b9484cSchristos   if (!result)
4898b9484cSchristos     return 0;
4998b9484cSchristos 
5098b9484cSchristos   result[len] = '\0';
5198b9484cSchristos   return (char *) memcpy (result, s, len);
5298b9484cSchristos }
53