From 38b001edbd06cce82c95cf7f367d6e60465d7311 Mon Sep 17 00:00:00 2001 From: Tobias Stoeckmann Date: Sat, 23 May 2020 12:34:40 +0200 Subject: [PATCH] Handle vsnprintf corner cases. The function vsnprintf returns a negative value on error, e.g. on an invalid format. It's best to return NULL in such a case. Also avoid a signed integer overflow if vsnprintf returns INT_MAX. This is undefined behaviour in C and has to be avoided. A negative value is returned with a call like: json_sprintf("%111111111111111s", "", ""); INT_MAX is returned with a call like: json_sprintf("%647s%2147483000s", "", ""); --- src/value.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/value.c b/src/value.c index a1a4705..c85a0b4 100644 --- a/src/value.c +++ b/src/value.c @@ -797,16 +797,18 @@ json_t *json_vsprintf(const char *fmt, va_list ap) { va_copy(aq, ap); length = vsnprintf(NULL, 0, fmt, ap); + if (length < 0) + goto out; if (length == 0) { json = json_string(""); goto out; } - buf = jsonp_malloc(length + 1); + buf = jsonp_malloc((size_t)length + 1); if (!buf) goto out; - vsnprintf(buf, length + 1, fmt, aq); + vsnprintf(buf, (size_t)length + 1, fmt, aq); if (!utf8_check_string(buf, length)) { jsonp_free(buf); goto out;