Namespaces
Variants
Actions

strdup

From cppreference.com
< c‎ | string‎ | byte
 
C
 
Strings library
 
Null-terminated byte strings
Functions
Character manipulation
Conversions to and from numeric formats
String manipulation
strdup
(C23)
(C23)

String examination
Memory manipulation
Miscellaneous
 
Defined in header <string.h>
char *strdup( const char *src );
(since C23)

Returns a pointer to a null-terminated byte string, which is a duplicate of the string pointed to by src. The space for the new string is obtained as if the malloc was invoked. The returned pointer must be passed to free to avoid a memory leak.

If an error occurs, a null pointer is returned and errno might be set.

Contents

[edit] Parameters

src - pointer to the null-terminated byte string to duplicate

[edit] Return value

A pointer to the newly allocated string, or a null pointer if an error occurred.

[edit] Notes

The function is identical to the POSIX strdup.

[edit] Example

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    const char *s1 = "Duplicate me!";
    char *s2 = strdup(s1);
    printf("s2 = \"%s\"\n", s2);
    free(s2);
}

Output:

s2 = "Duplicate me!"

[edit] See also

allocates a copy of a string of specified size
(function) [edit]
copies one string to another
(function) [edit]
allocates memory
(function) [edit]
deallocates previously allocated memory
(function) [edit]

Follow Lee on X/Twitter - Father, Husband, Serial builder creating AI, crypto, games & web tools. We are friends :) AI Will Come To Life!

Check out: eBank.nz (Art Generator) | Netwrck.com (AI Tools) | Text-Generator.io (AI API) | BitBank.nz (Crypto AI) | ReadingTime (Kids Reading) | RewordGame | BigMultiplayerChess | WebFiddle | How.nz | Helix AI Assistant