Index: src/string.c ================================================================== --- src/string.c +++ src/string.c @@ -36,23 +36,32 @@ struct CFWString { CFWObject obj; char *data; 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) { char *copy; size_t len; 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; return copy; @@ -62,19 +71,14 @@ cfw_strndup(const char *s, size_t max) { char *copy; size_t len; - len = strlen(s); - - if (len > max) - len = max; - - if ((copy = malloc(len + 1)) == NULL) { - errno = ENOMEM; - return NULL; - } + len = cfw_strnlen(s, max); + + if ((copy = malloc(len + 1)) == NULL) + return NULL; memcpy(copy, s, len); copy[len] = 0; return copy; Index: src/string.h ================================================================== --- src/string.h +++ src/string.h @@ -30,10 +30,11 @@ #include "class.h" #include "range.h" 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*); extern size_t cfw_string_length(CFWString*); extern bool cfw_string_set(CFWString*, const char*);