We could increment SIZE to ensure there would be room, but that would
disadvantage people using kstrings for binary data in power-of-2-sized
blocks. Instead document that SIZE=KS.l+1 will ensure NUL-termination.
This fixes a bug in the previous version when the l<m invariant does not
hold (kputc_()/etc and manual manipulation only maintain the weaker l<=m);
hattip Rob Davies.
}
#endif
+/* Ensures that the string has space for at least SIZE bytes, and ensures that
+ * it is NUL-terminated if there is room. Thus ks_resize(&s,s.l+1) can be used
+ * to make sure that a kstring_t is both allocated and NUL-terminated. */
static inline int ks_resize(kstring_t *s, size_t size)
{
if (s->m < size) {
else
return -1;
}
- s->s[s->l] = '\0';
+ if (s->l < s->m) s->s[s->l] = '\0';
return 0;
}