xstrndup.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /* Implement the xstrndup function.
  2. Copyright (C) 2005-2022 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 Replacement char* xstrndup (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. without fail, using @code{xmalloc} to obtain memory. The result is
  21. always NUL terminated.
  22. @end deftypefn
  23. */
  24. #ifdef HAVE_CONFIG_H
  25. #include "config.h"
  26. #endif
  27. #include <sys/types.h>
  28. #ifdef HAVE_STRING_H
  29. #include <string.h>
  30. #else
  31. # ifdef HAVE_STRINGS_H
  32. # include <strings.h>
  33. # endif
  34. #endif
  35. #include "ansidecl.h"
  36. #include "libiberty.h"
  37. char *
  38. xstrndup (const char *s, size_t n)
  39. {
  40. char *result;
  41. size_t len = strnlen (s, n);
  42. result = XNEWVEC (char, len + 1);
  43. result[len] = '\0';
  44. return (char *) memcpy (result, s, len);
  45. }