cJSON icon indicating copy to clipboard operation
cJSON copied to clipboard

cJSON_Version is not thread-safe

Open fekir opened this issue 1 year ago • 0 comments

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;
}

Suppose that two threads call cJSON_Version concurrently, there is a data race in version as sprintf modifies it, which results in UB.

Since the version is a constant, and CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR and CJSON_VERSION_PATCH are macros, probably the easiest fix is to use macros for creating the resulting string at compile-time

#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)

CJSON_PUBLIC(const char*) cJSON_Version(void)
{
    return STR(CJSON_VERSION_MAJOR) "." STR(CJSON_VERSION_MINOR) "." STR(CJSON_VERSION_PATCH) ;
}

fekir avatar Nov 02 '22 16:11 fekir