From 735d8becf2595c8fee990b55e2d323317f019c8d Mon Sep 17 00:00:00 2001 From: Danny van Kooten Date: Tue, 17 Mar 2020 15:22:27 +0100 Subject: grow buffer capacity exponentially --- src/template.c | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/template.c b/src/template.c index 0529c62..7aa3a75 100644 --- a/src/template.c +++ b/src/template.c @@ -1,5 +1,6 @@ #include #include +#include #include "vendor/mpc.h" #include "template.h" @@ -26,9 +27,16 @@ struct buffer { }; void buffer_reserve(struct buffer *buf, int l) { - if (buf->size + l >= buf->cap) { - buf->cap *= 2; - buf->string = realloc(buf->string, buf->size + l); + int req_size = buf->size + l; + if (req_size >= buf->cap) { + while (req_size >= buf->cap) { + buf->cap *= 2; + } + + buf->string = realloc(buf->string, buf->cap * sizeof *buf->string); + if (!buf->string) { + err(EXIT_FAILURE, "out of memory"); + } } } -- cgit v1.2.3