aboutsummaryrefslogtreecommitdiffstats
path: root/xstring.c
diff options
context:
space:
mode:
Diffstat (limited to 'xstring.c')
-rw-r--r--xstring.c31
1 files changed, 20 insertions, 11 deletions
diff --git a/xstring.c b/xstring.c
index 17804f3..09c6bf3 100644
--- a/xstring.c
+++ b/xstring.c
@@ -3,27 +3,36 @@
#include "xstring.h"
-string *string_alloc(const char *text)
+string *string_alloc(string *str, const char *text)
{
- return string_nalloc(text,
+ return string_nalloc(str, text,
(text) ? strlen(text) : INIT_LEN_STRING);
}
-string *string_nalloc(const char *text, size_t text_len)
+string *string_nalloc(string *str, const char *text, size_t text_len)
{
- string *str = malloc(sizeof(string));
- str->s = malloc(sizeof(char) * (text_len + 1));
+ if(!str) {
+ str = malloc(sizeof(string));
+ str->s = malloc(sizeof(char) * (text_len + 1));
+ str->capacity = text_len;
+ }
+ else {
+ if(text_len >= str->capacity) {
+ free(str->s);
+ str->s = malloc(sizeof(char) * (text_len + 1));
+ str->capacity = text_len;
+ }
+
+ }
+
if(text) {
strncpy(str->s, text, text_len);
- str->capacity = text_len;
str->len = text_len;
- str->s[text_len] = '\0';
}
- else {
+ else
str->len = 0;
- str->capacity = text_len;
- str->s[0] = '\0';
- }
+
+ str->s[str->len] = '\0';
return str;
}