From d34dda6d6e334737f5eabfca3231add23769be77 Mon Sep 17 00:00:00 2001 From: Nicolas Iooss Date: Tue, 14 May 2024 16:05:17 +0200 Subject: [PATCH] Compute cJSON_Version at compile time As CJSON_VERSION_... macros are known to be constant integers, it is possible to use C macros to transform them to literal strings and to directly use the result in function cJSON_Version. As a side-effect, this makes cJSON_Version thread-safe, as a there is no longer a shared buffer (static char version[15]) shared between threads. --- cJSON.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/cJSON.c b/cJSON.c index cac1164b..b2daa91f 100644 --- a/cJSON.c +++ b/cJSON.c @@ -121,12 +121,13 @@ CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item) #error cJSON.h and cJSON.c have different versions. Make sure that both have the same. #endif +#define STRINGIFY_(s) #s +#define STRINGIFY(s) STRINGIFY_(s) + CJSON_PUBLIC(const char*) cJSON_Version(void) { - static char version[15]; - sprintf(version, "%i.%i.%i", CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR, CJSON_VERSION_PATCH); - - return version; + return STRINGIFY(CJSON_VERSION_MAJOR) "." STRINGIFY(CJSON_VERSION_MINOR) "." \ + STRINGIFY(CJSON_VERSION_PATCH); } /* Case insensitive string comparison, doesn't consider two NULL pointers equal though */