The strdup() and strndup() functions are used to duplicate a string.
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:
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 (”) is added at the end.
Below is the C implementation to show the use of strndup() function in C:
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 contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Write one line functions for strcat() and strcmp()
- Functions that are executed before and after main() in C
- fill() and fill_n() functions in C++ STL
- Forward List in C++ | Set 1 (Introduction and Important Functions)
- strtok() and strtok_r() functions in C with examples
- Binary Search functions in C++ STL (binary_search, lower_bound and upper_bound)
- Ceil and Floor functions in C++
- Pure Virtual Functions and Abstract Classes in C++
- Wide char and library functions in C++
- Explicitly Defaulted and Deleted Functions in C++ 11
- atol(), atoll() and atof() functions in C/C++
- beta(), betaf() and betal() functions in C++ STL
- std::legendre, std::legendref and std::legendrel functions in C++17
- asctime() and asctime_s() functions in C with Examples
- Virtual Functions and Runtime Polymorphism in C++ | Set 1 (Introduction)
- asin() and atan() functions in C/C++ with Example
- isalpha() and isdigit() functions in C with cstring examples.
- Find and print duplicate words in std::vector<string> using STL functions
- Static functions in C
- Can static functions be virtual in C++?