DaveGamble / cJSON

Ultralightweight JSON parser in ANSI C
MIT License
10.28k stars 3.15k forks source link

print_number() non guaranteed to be thread safe with floating point numbers #853

Open escherstair opened 1 month ago

escherstair commented 1 month ago

print_number() seems to be an innocuous function because it prints a number into a string. Is uses sprintf (with different format specifiers "%d", "%1.15g", ... depending on the type) and so everything seems fine. But there is a big elephant in the room. Implementation of sprintf depends on the toolchain, and in the embedded world it would be one of newlib, newlib-nano, redlib, ... or something like that. Unfortunately, some of these implementations could call some malloc/calloc/realloc under the hood and this is a big issue when a RTOS is used. newlib calls allocators while formatting floating point numbers (not for integers). cJSON knows perfectly this problems with allocators and RTOS, and it provides cJSON_InitHooks to customize allocators. But there is no control over the allocators called by sprintf (as an example).

Long story short: formatting floating point numbers with newlib and RTOS cannot work. If you're interested you can read here

I think that cJSON should not depend on sprintf allocators, but include a working implementation of sprintf for floating point numbers.