Open In App

strdup() and strndup() functions in C/C++

Last Updated : 11 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The strdup() and strndup() functions are used to duplicate a string. 
strdup() : 
Syntax : char *strdup(const char *s); 
This function returns a pointer to a null-terminated byte string, which is a duplicate of the string pointed to by s. The memory obtained is done dynamically using malloc and hence it can be freed using free()
It returns a pointer to the duplicated string s.
Below is the C implementation to show the use of strdup() function in C:
 

C
// C program to demonstrate strdup()
#include<stdio.h>
#include<string.h>

int main()
{
    char source[] = "GeeksForGeeks";

    // A copy of source is created dynamically
    // and pointer to copy is returned.
    char* target = strdup(source); 

    printf("%s", target);
    return 0;
}

Output: 

GeeksForGeeks


strndup() : 
syntax: char *strndup(const char *s, size_t n); 
This function is similar to strdup(), but copies at most n bytes. 
Note: If s is longer than n, then only n bytes are copied, and a NULL ('\0') is added at the end.
Below is the C implementation to show the use of strndup() function in C:
 

C
// C program to demonstrate strndup()
#include<stdio.h>
#include<string.h>

int main()
{
    char source[] = "GeeksForGeeks";

    // 5 bytes of source are copied to a new memory
    // allocated dynamically and pointer to copied
    // memory is returned.
    char* target = strndup(source, 5);

    printf("%s", target);
    return 0;
}

Output:

Geeks

Let us see the differences in a tabular form -:

These functions are useful for duplicating strings in C++. The C++ Course provides insights into how to use strdup() and strndup() effectively, enhancing your string manipulation skills.

 strdup() strndup() 
1.It is used to return  a pointer to a null-terminated byte string,It is used to return  a pointer to a null-terminated byte string
2.Its syntax is -:
char * strdup( const char *str1 );

Its syntax is -:

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

3.It is defined in <string.h> header fileIt is defined in <string.h> header file
4.It only take one parameter that is pointer to the null-terminated byte string to duplicate

It takes two parameters that are -:
1.pointer to the null-terminated byte string to duplicate

2. max number of bytes to copy from str

5.Its return value is pointer to the newly allocated string.It returns a null pointer if an error occurred.


Reference: Linux man(7)
 


Next Article
Practice Tags :

Similar Reads