I have a pool of buffers used by several formatting functions. Here is a reduced example:
#include
#define COUNT_OF_BUFFERS 4
#define BUFFER_SIZE 256
static char pool_of_buffers[COUNT_OF_BUFFERS][BUFFER_SIZE];
static unsigned int next_buffer = 0;
char *get_next_buffer(void) {
next_buffer++;
if (next_buffer > COUNT_OF_BUFFERS) next_buffer = 0;
return &pool_of_buffers[next_buffer][0];
}
char *fmt_int(int i) {
char *buffer = get_next_buffer();
snprintf(buffer, BUFFER_SIZE, "%d", i);
return buffer;
}
char *fmt_long(long l) {
char *buffer = get_next_buffer();
snprintf(buffer, BUFFER_SIZE, "%ld", l);
return buffer;
}
int main(int argc, char **argv) {
printf("%s %s\n", fmt_int(1), fmt_long(2));
printf("%s %s %s %s %s %s\n", fmt_int(1), fmt_long(2), fmt_int(3), fmt_long(4),
fmt_int(5), fmt_long(6));
return 0;
}
As easily seen, that approach works as long as pool_of_buffers has enough buffers for all simultaneous calls from the same printf(). If number of calls to various fmt_*() functions exceed count of buffers in the pool - we have garbage.
The obvious solution I use in a production code - COUNT_OF_BUFFERS=64 and I hope no one is crazy enough to have 64+ calls in the same printf(). But it is a memory-hungry solution. Maybe someone can invent a trick so that get_next_buffer() can detect a case of too many calls from the same printf() and throw an error that pool is exhausted?