STRDUP(3)

NAME
strdup, strndup - save a copy of a string

SYNOPSIS
#include <string.h>
char *
strdup(const char *s);
char *
strndup(const char *s, size_t maxlen);

DESCRIPTION
The strdup() function allocates sufficient memory for a copy of the string s, does the copy, and returns a pointer to it. The pointer may subsequently be used as an argument to the function free(3).

The strndup() function behaves similarly to strdup but only copies up to maxlen characters from s. The resulting string is always NUL-terminated.

If insufficient memory is available, NULL is returned.

EXAMPLES
The following will point p to an allocated area of memory containing the NUL-terminated string "foobar":

    char *p;
    p = strdup("foobar");
    if (p == NULL)
    	err(1, NULL);

ERRORS
The strdup() and strndup() functions may fail and set the external variable errno for any of the errors specified for the library function malloc(3).

SEE ALSO
free(3), malloc(3), strcpy(3), strlcpy(3), strlen(3), wcsdup(3)

STANDARDS
The strdup() and strndup() functions conform to p1003.1-2008.

HISTORY
The strdup() function first appeared in 4.3BSD Reno. The strndup() function appeared in glibc 2.0, was reimplemented for NetBSD 4.0, and ported to OpenBSD 4.8.