Some people seem to think that C\'s strcpy()
function is bad or evil. While I admit that it\'s usually better to use strncpy()
in order to avoid bu
This answer uses size_t
and memcpy()
for a fast and simple strdup()
.
Best to use type size_t
as that is the type returned from strlen()
and used by malloc()
and memcpy()
. int
is not the proper type for these operations.
memcpy()
is rarely slower than strcpy()
or strncpy()
and often significantly faster.
// Assumption: `s1` points to a C string.
char *strdup(const char *s1) {
size_t size = strlen(s1) + 1;
char *s2 = malloc(size);
if(s2 != NULL) {
memcpy(s2, s1, size);
}
return s2;
}
§7.1.1 1 "A string is a contiguous sequence of characters terminated by and including the first null character. ..."