Your Own strdup() Function

In last week’s Lesson, I demonstrated the strdup() function. That function isn’t available in every C language library, but it’s easy to craft your own.

As a review, the strdup() function does two things:

1. Allocates space for a new string, setting the size the same as the original string
2. Copies the original string into the new allocated space, including the null character (\0)

If space can’t be allocated, the function returns a NULL pointer.

I called my faux strdup() function dupstring(), which is defined in the following code, a modification of the example from last week’s Lesson:

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

char *dupstring(char *org)
{
    int org_size;
    static char *dup;
    char *dup_offset;

    /* Allocate memory for duplicate */
    org_size = strlen(org);
    dup = (char *)malloc(sizeof(char)*org_size+1);
    if( dup == NULL)
        return( (char *)NULL);

    /* Copy string */
    dup_offset = dup;
    while(*org)
    {
        *dup_offset = *org;
        dup_offset++;
        org++;
    }
    *dup_offset = '\0';

    return(dup);
}

int main()
{
    char original[12] = "Ooga Booga!";
    char *duplicate;
    int o_len,d_len;

    duplicate = dupstring(original);
    o_len = strlen(original);
    d_len = strlen(duplicate);

    printf("Original String: '%s' (%d)\n",
            original,o_len);
    printf("Duplicate string: '%s' (%d)\n",
            duplicate,d_len);

    return(0);
}

The dupstring() function is declared at Line 5. The string created is held in the *dup pointer, which is made static at Line 8. It must be static, lest the string be lost when the function terminates.

The first step takes place at Lines 11 through 15, where storage for the duplicate string is allocated. The original string’s size is fetched (Line 12) and then the malloc() function allocates space for the duplicate, plus one character for the \0 (Line 13). Don’t forget that +1! The strlen() function doesn’t count the null character.

If the allocation fails, the NULL pointer is returned (Line 14 and 15).

After space is allocated, a while loop copies the original string into the duplicate. I use the dup_offset pointer so that the address of dup (the duplicate string) is retained.

Because the while loop doesn’t copy the null character, that character is appended to the duplicate string at Line 25. Then the duplicate string is returned.

Here’s sample output:

Original String: 'Ooga Booga!' (11)
Duplicate string: 'Ooga Booga!' (11)

Remember that the C language is written in the C language. Any function you desire, you can code. Even the strndup() function, which reads only the first n character of a string. Try it on your own!

Leave a Reply