ft_strdup.c 674 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /* Reproduce the behavior of the function strdup (man strdup) */
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. char *ft_strdup(char *src)
  6. {
  7. int i, len;
  8. char *copy;
  9. len = 0;
  10. i = 0;
  11. while (*src)
  12. len++;
  13. copy = (char*)malloc(sizeof(char) * (len + 1));
  14. if (copy == NULL)
  15. return (NULL);
  16. while (src[i])
  17. {
  18. copy[i] = src[i];
  19. i++;
  20. }
  21. copy[i] = '\0';
  22. return (copy);
  23. }
  24. int main(void)
  25. {
  26. char * a;
  27. char * b;
  28. char * c;
  29. char * d;
  30. char hi[3] = "Hi";
  31. char hello[12] = "Hello World";
  32. a = ft_strdup(hello);
  33. b = ft_strdup(hi);
  34. c = strdup(hello);
  35. d = strdup(hi);
  36. printf("%s, %s, %s, %s", a, b, c, d);
  37. return (0);
  38. }