[Solved] Understanding the strdup function


You are returning a pointer to the end of the string, and not the beginning of the string.

You need to return the pointer that malloc gave you. That’s what you placed in new_str in your initial assignment to new_str. But instead of returning that, you modify that pointer and then return it.

There are a lot of other problems with your code. For example at this point:

i = strlen(str + 1);

You calculate the length of the string that starts at str[1]. That will lead to undefined behaviour if your string is of length zero.

Perhaps you meant to write:

i = strlen(str) + 1;

In which case your call to malloc would be allocating too much.

Using sizeof(*new_str) is pointless since that is guaranteed to equal 1.

Anyway, rather than trying to remedy your code, here are some possible alternatives.

char *mystrdup(const char *str)
{
    char *result = malloc(strlen(str) + 1);
    char *psrc = str;
    char *pdst = result;
    while (*psrc != 0)
    {
        *pdst = *psrc;
        pdst++;
        psrc++;
    }
    *pdst="\0";
    return result;
}

You could make the body of the loop more concise like this:

*pdst++ = *psrc++;

You could do it with a for loop:

char *mystrdup(const char *str)
{
    size_t len = strlen(str);
    char *result = malloc(len + 1);
    for (size_t i = 0; i <= len; i++)
        result[i] = str[i];
    return result;
}

Or you could even using memcpy like this:

char *mystrdup(const char *str)
{
    size_t len = strlen(str);
    char *result = malloc(len + 1);
    memcpy(result, str, len + 1);
    return result;
}

Note that in all cases the value that I get back from malloc is returned unmodified.

I’ve ignored the possible error condition on the calls to malloc. You can worry about that!

2

solved Understanding the strdup function