From d07da04c14d9677506e95aa58dc0cb10322ed79f Mon Sep 17 00:00:00 2001 From: Tobias Stoeckmann Date: Thu, 3 Mar 2022 21:24:27 +0100 Subject: [PATCH] sprintbuf(): handle printbuf_memappend errors If errors occur in printbuf_memappend, then these errors should be propagated through sprintbuf to indicate the error to the user. Proof of Concept: ``` #include #include #include #include "json.h" int main(void) { struct printbuf *pb; if ((pb = printbuf_new()) == NULL) err(1, "printbuf_new"); if (printbuf_memset(pb, INT_MAX - 9, 'a', 1) < 0) errx(1, "printbuf_memset"); printf("length: %d\n", printbuf_length(pb)); printf("sprintbuf: %d\n", sprintbuf(pb, "string too long")); printf("length: %d\n", printbuf_length(pb)); printbuf_free(pb); return 0; } ``` You can see that sprintbuf does not return an error but length is still the same, i.e. the string "string too long" has not been appended. I would like to add this as a unit test but it really depends on the operating system if printbuf_memset() would fail if not enough memory is available or not. --- printbuf.c | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/printbuf.c b/printbuf.c index 00822fac..48e8101e 100644 --- a/printbuf.c +++ b/printbuf.c @@ -152,15 +152,14 @@ int sprintbuf(struct printbuf *p, const char *msg, ...) return -1; } va_end(ap); - printbuf_memappend(p, t, size); + size = printbuf_memappend(p, t, size); free(t); - return size; } else { - printbuf_memappend(p, buf, size); - return size; + size = printbuf_memappend(p, buf, size); } + return size; } void printbuf_reset(struct printbuf *p) -- 2.39.5