diff --git a/src/string.c b/src/string.c index 1fae4bc..42638c4 100644 --- a/src/string.c +++ b/src/string.c @@ -39,6 +39,17 @@ struct CFWString { size_t len; }; +size_t +cfw_strnlen(const char *s, size_t max) +{ + size_t i = 0; + + for (i = 0; i < max && *s != '\0'; s++) + i++; + + return i; +} + char* cfw_strdup(const char *s) { @@ -47,10 +58,8 @@ cfw_strdup(const char *s) len = strlen(s); - if ((copy = malloc(len + 1)) == NULL) { - errno = ENOMEM; + if ((copy = malloc(len + 1)) == NULL) return NULL; - } memcpy(copy, s, len); copy[len] = 0; @@ -64,15 +73,10 @@ cfw_strndup(const char *s, size_t max) char *copy; size_t len; - len = strlen(s); + len = cfw_strnlen(s, max); - if (len > max) - len = max; - - if ((copy = malloc(len + 1)) == NULL) { - errno = ENOMEM; + if ((copy = malloc(len + 1)) == NULL) return NULL; - } memcpy(copy, s, len); copy[len] = 0; diff --git a/src/string.h b/src/string.h index 73d33c0..45dfe59 100644 --- a/src/string.h +++ b/src/string.h @@ -32,6 +32,7 @@ typedef struct CFWString CFWString; extern CFWClass *cfw_string; +extern size_t cfw_strnlen(const char*, size_t); extern char* cfw_strdup(const char*); extern char* cfw_strndup(const char*, size_t); extern const char* cfw_string_c(CFWString*);