Fix cfw_strndup() and add cfw_strnlen().

This commit is contained in:
Jonathan Schleifer 2012-09-30 02:59:17 +02:00
parent f9171cf8a1
commit 8f0ffd2483
2 changed files with 15 additions and 10 deletions

View file

@ -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;

View file

@ -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*);