Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

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

  • Difficulty Level : Medium
  • Last Updated : 10 Jun, 2021

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:
 

Take a step-up from those "Hello World" programs. Learn to implement data structures like Heap, Stacks, Linked List and many more! Check out our Data Structures in C course to start learning today.

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

Reference: Linux man(7)
This article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 




My Personal Notes arrow_drop_up
Recommended Articles
Page :