strndup.c 489 B

12345678910111213141516171819202122232425
  1. /*
  2. * Copyright (C) 2002 Manuel Novoa III
  3. * Copyright (C) 2000-2005 Erik Andersen <andersen@uclibc.org>
  4. *
  5. * Licensed under the LGPL v2.1, see the file COPYING.LIB in this tarball.
  6. */
  7. #include "_string.h"
  8. #include <stdlib.h>
  9. char *strndup(register const char *s1, size_t n)
  10. {
  11. register char *s;
  12. n = strnlen(s1,n); /* Avoid problems if s1 not nul-terminated. */
  13. if ((s = malloc(n + 1)) != NULL) {
  14. memcpy(s, s1, n);
  15. s[n] = 0;
  16. }
  17. return s;
  18. }
  19. libc_hidden_def(strndup)