strdup()

Updated: April 19, 2023

Create a duplicate of a string

Synopsis:

#include <string.h>

char* strdup( const char* src );

Arguments:

src
The string that you want to copy.

Library:

libc

Use the -l c option to qcc to link against this library. This library is usually included automatically.

Description:

The strdup() function creates a duplicate of the string pointed to by src, and returns a pointer to the new copy.

Note: The strdup() function allocates the memory for the new string by calling malloc(); it's up to you to release the memory by calling free().

Returns:

A pointer to a copy of the string, or NULL if an error occurred (errno) is set.

Errors:

ENOMEM
Not enough memory.

Examples:

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

int main( void )
{
    char *dup;

    dup = strdup( "Make a copy" );
    printf( "%s\n", dup );
    free (dup);

    return EXIT_SUCCESS;
}

Classification:

POSIX 1003.1

Safety:  
Cancellation point No
Interrupt handler No
Signal handler No
Thread Yes