cJSON icon indicating copy to clipboard operation
cJSON copied to clipboard

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

Open escherstair opened this issue 1 year ago • 0 comments
trafficstars

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.

escherstair avatar May 08 '24 11:05 escherstair