1169695Skan/* Implement the strndup function. 2169695Skan Copyright (C) 2005 Free Software Foundation, Inc. 3169695Skan Written by Kaveh R. Ghazi <ghazi@caip.rutgers.edu>. 4169695Skan 5169695SkanThis file is part of the libiberty library. 6169695SkanLibiberty is free software; you can redistribute it and/or 7169695Skanmodify it under the terms of the GNU Library General Public 8169695SkanLicense as published by the Free Software Foundation; either 9169695Skanversion 2 of the License, or (at your option) any later version. 10169695Skan 11169695SkanLibiberty is distributed in the hope that it will be useful, 12169695Skanbut WITHOUT ANY WARRANTY; without even the implied warranty of 13169695SkanMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 14169695SkanLibrary General Public License for more details. 15169695Skan 16169695SkanYou should have received a copy of the GNU Library General Public 17169695SkanLicense along with libiberty; see the file COPYING.LIB. If 18169695Skannot, write to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor, 19169695SkanBoston, MA 02110-1301, USA. */ 20169695Skan 21169695Skan/* 22169695Skan 23169695Skan@deftypefn Extension char* strndup (const char *@var{s}, size_t @var{n}) 24169695Skan 25169695SkanReturns a pointer to a copy of @var{s} with at most @var{n} characters 26169695Skanin memory obtained from @code{malloc}, or @code{NULL} if insufficient 27169695Skanmemory was available. The result is always NUL terminated. 28169695Skan 29169695Skan@end deftypefn 30169695Skan 31169695Skan*/ 32169695Skan 33169695Skan#include "ansidecl.h" 34169695Skan#include <stddef.h> 35169695Skan 36169695Skanextern size_t strlen (const char*); 37169695Skanextern PTR malloc (size_t); 38169695Skanextern PTR memcpy (PTR, const PTR, size_t); 39169695Skan 40169695Skanchar * 41169695Skanstrndup (const char *s, size_t n) 42169695Skan{ 43169695Skan char *result; 44169695Skan size_t len = strlen (s); 45169695Skan 46169695Skan if (n < len) 47169695Skan len = n; 48169695Skan 49169695Skan result = (char *) malloc (len + 1); 50169695Skan if (!result) 51169695Skan return 0; 52169695Skan 53169695Skan result[len] = '\0'; 54169695Skan return (char *) memcpy (result, s, len); 55169695Skan} 56