strndup.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /* Implement the strndup function.
  2. Copyright (C) 2005 Free Software Foundation, Inc.
  3. Written by Kaveh R. Ghazi <ghazi@caip.rutgers.edu>.
  4. This file is part of the libiberty library.
  5. Libiberty is free software; you can redistribute it and/or
  6. modify it under the terms of the GNU Library General Public
  7. License as published by the Free Software Foundation; either
  8. version 2 of the License, or (at your option) any later version.
  9. Libiberty is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. Library General Public License for more details.
  13. You should have received a copy of the GNU Library General Public
  14. License along with libiberty; see the file COPYING.LIB. If
  15. not, write to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
  16. Boston, MA 02110-1301, USA. */
  17. /*
  18. @deftypefn Extension char* strndup (const char *@var{s}, size_t @var{n})
  19. Returns a pointer to a copy of @var{s} with at most @var{n} characters
  20. in memory obtained from @code{malloc}, or @code{NULL} if insufficient
  21. memory was available. The result is always NUL terminated.
  22. @end deftypefn
  23. */
  24. #include "ansidecl.h"
  25. #include <stddef.h>
  26. extern size_t strlen (const char*);
  27. extern PTR malloc (size_t);
  28. extern PTR memcpy (PTR, const PTR, size_t);
  29. char *
  30. strndup (const char *s, size_t n)
  31. {
  32. char *result;
  33. size_t len = strlen (s);
  34. if (n < len)
  35. len = n;
  36. result = (char *) malloc (len + 1);
  37. if (!result)
  38. return 0;
  39. result[len] = '\0';
  40. return (char *) memcpy (result, s, len);
  41. }