1 /* 2 Copyright (c) 2002 Jeff Johnston <jjohnstn@redhat.com> 3 */ 4 5 #define _DEFAULT_SOURCE 6 #include <stdlib.h> 7 #include <string.h> 8 9 char * strndup(const char * str,size_t n)10strndup (const char *str, 11 size_t n) 12 { 13 const char *ptr = str; 14 size_t len; 15 char *copy; 16 17 while (n-- > 0 && *ptr) 18 ptr++; 19 20 len = ptr - str; 21 22 copy = malloc (len + 1); 23 if (copy) 24 { 25 memcpy (copy, str, len); 26 copy[len] = '\0'; 27 } 28 return copy; 29 } 30