MULE 0.0.1
Multi-Use Library Essentials
Loading...
Searching...
No Matches
02_reuse.c

Clear and refill one Str in a loop, so one allocation serves every pass.

/* Str on its own: clear and refill one buffer instead of allocating per line.
*/
#include "mem/mem.c"
#include "str/str.c"
#include <stdio.h>
#include <stdlib.h>
int main(void) {
Str line = { 0 };
for (int part = 1; part <= 3; part++) {
str_clear(&line);
if (!str_appendf(&line, "PART %d", part)) {
str_free(&line);
return EXIT_FAILURE;
}
printf("%-8s capacity %zu, data %p\n", str_cstr(&line), line.capacity,
(void *)line.data);
}
str_free(&line);
return EXIT_SUCCESS;
}
size_t capacity
Content bytes that fit before the next realloc.
Definition str.h:67
char * data
Buffer, or null when nothing is allocated.
Definition str.h:65
const char * str_cstr(const Str *s)
NUL-terminated contents of s, for C APIs such as fopen and puts.
Definition str.c:216
void str_clear(Str *s)
Set the length to zero.
Definition str.c:71
void str_free(Str *s)
Free the buffer and reset s to the zero state.
Definition str.c:50
bool str_appendf(Str *s, const char *fmt,...)
Append the printf-style expansion of fmt.
Definition str.c:123
Owned, growable byte string.
Definition str.h:64