From 8f0ffd2483b8cf3c1ce387d2563051e38cf62323 Mon Sep 17 00:00:00 2001 From: Jonathan Schleifer Date: Sun, 30 Sep 2012 02:59:17 +0200 Subject: [PATCH] Fix cfw_strndup() and add cfw_strnlen(). --- src/string.c | 24 ++++++++++++++---------- src/string.h | 1 + 2 files changed, 15 insertions(+), 10 deletions(-) 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*);