strndup()

Updated: April 19, 2023

Create a duplicate of a string, up to a maximum length

Synopsis:

#include <string.h>

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

Arguments:

src
The string that you want to copy.
size
The maximum number of bytes to copy.

Library:

libc

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

Description:

The strndup() function calls malloc() to allocate up to size + 1 bytes of memory, copies at most size bytes from the original string, terminates the new string with a NUL character, and returns a pointer to the new string.

Note: It's up to you to release the memory by calling free(). Don't assume that strndup() allocates size + 1 bytes when src is less than size bytes long.

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 = strndup( "Make a copy", 10 );
    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