strndup

From cppreference.com
< c‎ | experimental‎ | dynamic
Defined in header <string.h>
char *strndup(const char *str, size_t size);
(dynamic memory TR)

Returns a pointer to a null-terminated byte string, which contains copies of at most size bytes from the string pointed to by str. If the null terminator is not encountered in the first size bytes, it is added to the duplicated string.

The returned pointer must be passed to free to avoid a memory leak.

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

As all functions from Dynamic Memory TS, strndup is only guaranteed to be available if __STDC_ALLOC_LIB__ is defined by the implementation and if the user defines __STDC_WANT_LIB_EXT2__ to the integer constant 1 before including string.h.

Contents

[edit] Parameters

str - pointer to the null-terminated byte string to duplicate
size - max number of bytes to copy from str

[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 strndup except that it is allowed, but not required to set errno on error.

[edit] Example

#define __STDC_WANT_LIB_EXT2__ 1
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
 
int main()
{
    char *s1 = "String";
    char *s2 = strndup(s1, 2);
    printf("strndup(\"String\", 2) == %s\n", s2);
    free(s2);
}

Output:

strndup("String", 2) == St

[edit] See also

(dynamic memory TR)
allocate a copy of a string
(function)
copies a certain amount of characters from one string to another
(function)
allocates memory
(function)