What is the purpose of the strdup()
function in C?
The most valuable thing it does is give you another string identical to the first, without requiring you to allocate memory (location and size) yourself. But, as noted, you still need to free it (but which doesn't require a quantity calculation, either.)
char * strdup(const char * s)
{
size_t len = 1+strlen(s);
char *p = malloc(len);
return p ? memcpy(p, s, len) : NULL;
}
Maybe the code is a bit faster than with strcpy()
as the \0
char doesn't need to be searched again (It already was with strlen()
).
strdup
and strndup
are defined in POSIX compliant systems as:
char *strdup(const char *str);
char *strndup(const char *str, size_t len);
The strdup() 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
.
If insufficient memory is available, NULL
is returned and errno
is set to
ENOMEM
.
The strndup() function copies at most len
characters from the string str
always null terminating the copied string.
From strdup man:
The strdup()
function shall return a pointer to a new string, which is a duplicate of the string pointed to by s1
. The returned pointer can be passed to free()
. A null pointer is returned if the new string cannot be created.