Implementation of strdup() in C programming

Try following fix:

  1. Initialize len before increment it.
  2. Don't cast malloc's return value, and don't use sizeof(char), it's defined to be 1 in the standard, per cstd 6.5.3.4p4:

    When sizeof is applied to an operand that has type char, unsigned char, or signed char, (or a qualified version thereof) the result is 1.

  3. Use a pointer to save the original str pointer

#include <stdlib.h>

char *ft_strdup(char *src)
{
    char *str;
    char *p;
    int len = 0;

    while (src[len])
        len++;
    str = malloc(len + 1);
    p = str;
    while (*src)
        *p++ = *src++;
    *p = '\0';
    return str;
}

If you must implement your own strdup function, at least rely on the rest of string.h for as much as you can. Many of these functions are optimized, and faster than you can write them yourself. For example, strlen is probably using SSE instructions, while your manual search for the null-terminator byte is not. It's also less code, which is always better. In short, I would suggest this:

#include <stdlib.h>
#include <string.h>

char *ft_strdup(const char *s1)
{
  char *str;
  size_t size = strlen(s1) + 1;

  str = malloc(size);
  if (str) {
    memcpy(str, s1, size);
  }
  return str;
}

Tags:

C