A Guide to using the strdup() function in C/C++

Filed Under: C Programming
Strdup In C

In this article, we’ll take a look at using the strdup() function in C/C++.

The strdup() function is very useful if you want to duplicate the contents of a string onto another string.

Let’s see how we can utilize this function, using some simple examples.


Basic Syntax of the strdup() function in C/C++

This takes in an input char* string, and duplicates it into another char* string. It returns the pointer to this string.

This is also defined inside the header file <string.h>, so we must include it first.

Therefore, the function prototype is as follows:

#include <string.h>
char* strdup(const char* src);

Since we will not be modifying the input string, we pass it as const char*!

NOTE: This function is NOT defined in the ISO C99 standards, but it is defined in POSIX systems. If you’re unsure about using this function, refer to the below section for a sample implementation.

Let’s now look at a simple example, which shows this function coming into play.


Using strdup() – A simple Example

We’ll take an input string, and copy it into another string.

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

int main() {
    char inp[] = "Hello from JournalDev!";
    char* output = strdup(inp);
    printf("Input: %s\n", inp);
    printf("Output: %s\n", output);
    return 0;
}

Output

Input: Hello from JournalDev!
Output: Hello from JournalDev!

As you can see, we do indeed get our output to be the same string as the input.


Using strdup() vs Using strcpy()

You may very well wonder – if strdup() duplicates an input string, and strcpy() copies from an input string, what is the difference?

The difference between the two lies in how these two functions are implemented.

When you use strcpy(dst, src), you are literally copying from the source string to the destination string. Here, you are responsible for both allocating and de-allocating the memory with dst.

This is because strcpy simply copies data. Here is an elegant one-line implementation from this StackOverflow answer!

void strcpy(char* dst, char* src) {
    while (*dst++ = *src++);
}

What does this imply? This means that you can use strcpy() on both static (associated with stack) memory as well as dynamic (associated with heap) memory.

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

int main() {
    char a[] = "Hello";
    // Memory associated with stack
    char b[100];
    
    strcpy(b, a);

    // Memory associated with heap
    char* c = (char*) malloc (10 * sizeof(char));
    strcpy(b, c);
    
    printf("a = %s\nb=%s\nc=%s\n", a, b);
    free(c);
    return 0;
}

Output

a = Hello
b = Hello
c = Hello

Indeed, we could copy to both static as well as dynamic memory locations, using strcpy().

Now, strdup() uses malloc() under the hood to automatically allocate the memory for you. However, this means that you must free the memory yourself, after you finish using it!

So, simply put, strdup() allocates memory using malloc(), and then copies your source string to the allocated memory.

A Sample Implementation of strdup()

Here is an efficient implementation, using memcpy() to speed things up, as compared to naive copying using strcpy().

char* my_strdup(char* input) {
    // We need strlen(src) + 1, since we have to account for '\0'
    int len = strlen(input) + 1;
    char* output = (char*) malloc ((len + 1) * sizeof(char));
    if (output == NULL) return NULL;
    output = (char*) memcpy(output, input, len);
    return output;
}

Now, let’s look at a complete program, to verify that we can use this properly. Remember, we must also free the memory returned by malloc()!

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

char* my_strdup(char* input) {
    // We need strlen(src) + 1, since we have to account for '\0'
    int len = strlen(input) + 1;
    char* output = (char*) malloc ((len + 1) * sizeof(char));
    if (output == NULL) return NULL;
    output = (char*) memcpy(output, input, len);
    return output;
}

int main() {
    char inp[] = "Hello from JournalDev!";
    char* output = my_strdup(inp);
    printf("Input: %s\n", inp);
    printf("Output: %s\n", output);
    // Free the memory address returned using malloc()
    free(output);
    return 0;
}

Output

Input: Hello from JournalDev!
Output: Hello from JournalDev!

Indeed, we did get the same output as before! And we don’t seem to have any memory leaks, since we freed the corresponding memory at the end.


Conclusion

We learned about we could use the strdup() function in C/C++. We also learned about the differences between strdup() and strcpy(), so use them wisely!

For similar content, do check out our tutorial section on C programming!

References


Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages