STRDUP(3) Library Functions Manual STRDUP(3)

strdup, strndupsave a copy of a string

Standard C Library (libc, -lc)

#include <string.h>

char *
strdup(const char *str);

char *
strndup(const char *str, size_t len);

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

If insufficient memory is available, NULL is returned.

The () function copies at most len characters from the string str always NUL terminating the copied string.

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

char *p;

if ((p = strdup("foobar")) == NULL) {
	fprintf(stderr, "Out of memory.\n");
	exit(1);
}

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

free(3), malloc(3), strcpy(3), strlen(3)

The strdup() function conforms to IEEE Std 1003.1-2001 (“POSIX.1”). The strdup() and strndup() functions conform to ISO/IEC 9899:2024 (“ISO C23”).

The strdup() function first appeared in 4.4BSD. The strndup() function was added in NetBSD 4.0.

December 9, 2024 NetBSD 11.0