strndup.c 1.0 KB

123456789101112131415161718192021222324252627282930313233343536
  1. /* A replacement function, for systems that lack strndup.
  2. Copyright (C) 1996-1998, 2001-2003, 2005-2007, 2009-2013 Free Software
  3. Foundation, Inc.
  4. This program is free software; you can redistribute it and/or modify it
  5. under the terms of the GNU General Public License as published by the
  6. Free Software Foundation; either version 3, or (at your option) any
  7. later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, see <http://www.gnu.org/licenses/>. */
  14. #include <config.h>
  15. #include <string.h>
  16. #include <stdlib.h>
  17. char *
  18. strndup (char const *s, size_t n)
  19. {
  20. size_t len = strnlen (s, n);
  21. char *new = malloc (len + 1);
  22. if (new == NULL)
  23. return NULL;
  24. new[len] = '\0';
  25. return memcpy (new, s, len);
  26. }