diff options
author | Joursoir <chat@joursoir.net> | 2021-05-17 08:22:23 +0000 |
---|---|---|
committer | Joursoir <chat@joursoir.net> | 2021-05-17 08:34:46 +0000 |
commit | 58241bc88020e972b7719753c3838a5557ac4d84 (patch) | |
tree | 3f6bcdaac3851773e12e9572e63bd23943808c6d | |
parent | e7acb77a45d3163e2e1b1da0558d50b7b28f9d8f (diff) | |
download | ctimeline-58241bc88020e972b7719753c3838a5557ac4d84.tar.gz ctimeline-58241bc88020e972b7719753c3838a5557ac4d84.tar.bz2 ctimeline-58241bc88020e972b7719753c3838a5557ac4d84.zip |
xstring: extend memory allocation
-rw-r--r-- | xstring.c | 31 | ||||
-rw-r--r-- | xstring.h | 1 |
2 files changed, 25 insertions, 7 deletions
@@ -5,18 +5,23 @@ string *string_alloc(const char *text)
{
+ return string_nalloc(text,
+ (text) ? strlen(text) : INIT_LEN_STRING);
+}
+
+string *string_nalloc(const char *text, size_t text_len)
+{
string *str = malloc(sizeof(string));
+ str->s = malloc(sizeof(char) * (text_len + 1));
if(text) {
- int length = strlen(text);
- str->s = malloc(sizeof(char) * (length + 1));
- strcpy(str->s, text);
- str->capacity = length;
- str->len = length;
+ strncpy(str->s, text, text_len);
+ str->capacity = text_len;
+ str->len = text_len;
+ str->s[text_len] = '\0';
}
else {
- str->s = malloc(sizeof(char) * (INIT_LEN_STRING + 1));
str->len = 0;
- str->capacity = INIT_LEN_STRING;
+ str->capacity = text_len;
str->s[0] = '\0';
}
return str;
@@ -39,6 +44,18 @@ void string_reset(string *str) }
}
+static void string_realloc(string *str, int cap)
+{
+ int i;
+ char *tmp_s = str->s;
+ str->s = malloc(sizeof(char) * (cap + 1));
+ for(i = 0; i < cap; i++)
+ str->s[i] = (i >= str->len) ? '\0' : tmp_s[i];
+
+ str->capacity = cap;
+ free(tmp_s);
+}
+
void string_addch(string *str, int ch)
{
if(str->capacity <= (str->len + 1)) {
@@ -10,6 +10,7 @@ typedef struct tag_string { } string; string *string_alloc(const char *text); +string *string_nalloc(const char *text, size_t text_len); void string_release(string *str); void string_reset(string *str); void string_addch(string *str, int ch); |