Step 9 of 9
Challenge: a string builder
Building a long string with repeated strcat into a fixed buffer is how buffer overflows happen. Real C code uses a string builder: a struct that owns a growing heap buffer.
typedef struct {
char *buf; /* always '\0'-terminated once initialized */
size_t len; /* characters used, not counting '\0' */
size_t cap; /* bytes allocated */
} Builder;
Your turn: write the four functions:
sb_init(b): allocate a small starting buffer (say 8 bytes) holding"". Return 0 on success, -1 if allocation fails.sb_append(b, s): appends, doublingcapas many times as needed. Return 0, or -1 ifreallocfails (leavebunchanged then).sb_str(b): return the current string.sb_free(b): free the buffer and reset the fields.