Remove sprintf() from cJSON.

This commit is contained in:
antirez 2025-03-27 12:19:56 +01:00
parent b17499f907
commit 4dca45ad24
1 changed files with 7 additions and 7 deletions

14
cJSON.c
View File

@ -124,7 +124,7 @@ CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item)
CJSON_PUBLIC(const char*) cJSON_Version(void) CJSON_PUBLIC(const char*) cJSON_Version(void)
{ {
static char version[15]; static char version[15];
sprintf(version, "%i.%i.%i", CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR, CJSON_VERSION_PATCH); snprintf(version, sizeof(version), "%i.%i.%i", CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR, CJSON_VERSION_PATCH);
return version; return version;
} }
@ -579,26 +579,26 @@ static cJSON_bool print_number(const cJSON * const item, printbuffer * const out
/* This checks for NaN and Infinity */ /* This checks for NaN and Infinity */
if (isnan(d) || isinf(d)) if (isnan(d) || isinf(d))
{ {
length = sprintf((char*)number_buffer, "null"); length = snprintf((char*)number_buffer, sizeof(number_buffer), "null");
} }
else if(d == (double)item->valueint) else if(d == (double)item->valueint)
{ {
length = sprintf((char*)number_buffer, "%d", item->valueint); length = snprintf((char*)number_buffer, sizeof(number_buffer), "%d", item->valueint);
} }
else else
{ {
/* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */ /* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */
length = sprintf((char*)number_buffer, "%1.15g", d); length = snprintf((char*)number_buffer, sizeof(number_buffer), "%1.15g", d);
/* Check whether the original double can be recovered */ /* Check whether the original double can be recovered */
if ((sscanf((char*)number_buffer, "%lg", &test) != 1) || !compare_double((double)test, d)) if ((sscanf((char*)number_buffer, "%lg", &test) != 1) || !compare_double((double)test, d))
{ {
/* If not, print with 17 decimal places of precision */ /* If not, print with 17 decimal places of precision */
length = sprintf((char*)number_buffer, "%1.17g", d); length = snprintf((char*)number_buffer, sizeof(number_buffer), "%1.17g", d);
} }
} }
/* sprintf failed or buffer overrun occurred */ /* snprintf failed or buffer overrun occurred */
if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1))) if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1)))
{ {
return false; return false;
@ -1028,7 +1028,7 @@ static cJSON_bool print_string_ptr(const unsigned char * const input, printbuffe
break; break;
default: default:
/* escape and print as unicode codepoint */ /* escape and print as unicode codepoint */
sprintf((char*)output_pointer, "u%04x", *input_pointer); snprintf((char*)output_pointer, sizeof(output_pointer), "u%04x", *input_pointer);
output_pointer += 4; output_pointer += 4;
break; break;
} }