From 400a92fa0461d128cc0a74e9a0f6fde48854850f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Ekl=C3=B6f?= Date: Mon, 7 Jan 2019 18:26:48 +0100 Subject: [PATCH] tag: rename and rewrite sbuf_strcat() In particular, don't use strncat() with a length derived from the source. --- tag.c | 30 ++++++++++++++---------------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/tag.c b/tag.c index 86b8406..5a3e40e 100644 --- a/tag.c +++ b/tag.c @@ -373,27 +373,25 @@ struct sbuf { }; static void -sbuf_strncat(struct sbuf *s1, const char *s2, size_t n) +sbuf_append_at_most(struct sbuf *s1, const char *s2, size_t n) { - size_t s2_actual_len = strlen(s2); - size_t s2_len = s2_actual_len < n ? s2_actual_len : n; - - if (s1->len + s2_len >= s1->size) { - size_t required_size = s1->len + s2_len + 1; + if (s1->len + n >= s1->size) { + size_t required_size = s1->len + n + 1; s1->size = 2 * required_size; s1->s = realloc(s1->s, s1->size); - s1->s[s1->len] = '\0'; + //s1->s[s1->len] = '\0'; } - strncat(s1->s, s2, s2_len); - s1->len += s2_len; + memcpy(&s1->s[s1->len], s2, n); + s1->len += n; + s1->s[s1->len] = '\0'; } static void -sbuf_strcat(struct sbuf *s1, const char *s2) +sbuf_append(struct sbuf *s1, const char *s2) { - sbuf_strncat(s1, s2, strlen(s2)); + sbuf_append_at_most(s1, s2, strlen(s2)); } char * @@ -409,7 +407,7 @@ tags_expand_template(const char *template, const struct tag_set *tags) if (begin == NULL) { /* No more tags, copy remaining characters */ - sbuf_strcat(&formatted, template); + sbuf_append(&formatted, template); break; } @@ -417,7 +415,7 @@ tags_expand_template(const char *template, const struct tag_set *tags) const char *end = strchr(begin, '}'); if (end == NULL) { /* Wasn't actually a tag, copy as-is instead */ - sbuf_strncat(&formatted, template, begin - template + 1); + sbuf_append_at_most(&formatted, template, begin - template + 1); template = begin + 1; continue; } @@ -431,17 +429,17 @@ tags_expand_template(const char *template, const struct tag_set *tags) const struct tag *tag = tag_for_name(tags, tag_name); if (tag == NULL) { /* No such tag, copy as-is instead */ - sbuf_strncat(&formatted, template, begin - template + 1); + sbuf_append_at_most(&formatted, template, begin - template + 1); template = begin + 1; continue; } /* Copy characters preceeding the tag (name) */ - sbuf_strncat(&formatted, template, begin - template); + sbuf_append_at_most(&formatted, template, begin - template); /* Copy tag value */ const char *value = tag->as_string(tag); - sbuf_strcat(&formatted, value); + sbuf_append(&formatted, value); /* Skip past tag name + closing '}' */ template = end + 1;