From: Tobias Stoeckmann Date: Thu, 3 Mar 2022 20:24:27 +0000 (+0100) Subject: sprintbuf(): handle printbuf_memappend errors X-Git-Tag: json-c-0.16-20220414~14^2 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=refs%2Fpull%2F749%2Fhead;p=thirdparty%2Fjson-c.git 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. --- 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)