strdup() and strdndup() in C/C++

The functions strdup() and strndup() are used to duplicate strings in C. These functions allocate memory dynamically and create copies of existing strings. Note that these are POSIX functions, not part of the C standard library.

Note: To use strdup() and strndup(), you may need to compile with -D_GNU_SOURCE flag or ensure your system supports POSIX extensions.

strdup() Function

The strdup() function duplicates an entire string by allocating memory and copying the string content.

Syntax

char *strdup(const char *string);

Parameters

  • string − Pointer to the null-terminated string to be duplicated

Return Value

Returns a pointer to the newly allocated string, or NULL if allocation fails.

Example

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

int main() {
    char *str = "Helloworld";
    char *result;
    
    result = strdup(str);
    if (result != NULL) {
        printf("Original string: %s\n", str);
        printf("Duplicated string: %s\n", result);
        free(result);  // Always free allocated memory
    } else {
        printf("Memory allocation failed\n");
    }
    
    return 0;
}
Original string: Helloworld
Duplicated string: Helloworld

strndup() Function

The strndup() function duplicates at most n characters from a string, automatically null-terminating the result.

Syntax

char *strndup(const char *string, size_t size);

Parameters

  • string − Pointer to the source string
  • size − Maximum number of characters to copy

Example

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

int main() {
    char *str = "Helloworld";
    char *result;
    
    result = strndup(str, 5);
    if (result != NULL) {
        printf("Original string: %s\n", str);
        printf("Duplicated string (first 5 chars): %s\n", result);
        printf("Length of duplicated string: %lu\n", strlen(result));
        free(result);
    } else {
        printf("Memory allocation failed\n");
    }
    
    return 0;
}
Original string: Helloworld
Duplicated string (first 5 chars): Hello
Length of duplicated string: 5

Key Points

  • Both functions allocate memory dynamically − always use free() to prevent memory leaks
  • Always check for NULL return value to handle allocation failures
  • strndup() is safer for partial string copying as it limits the copy length
  • These are POSIX functions, not standard C library functions

Conclusion

The strdup() and strndup() functions provide convenient ways to duplicate strings with dynamic memory allocation. Remember to always free the allocated memory and check for allocation failures in production code.

Updated on: 2026-03-15T09:54:35+05:30

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements