I am running an embedded system with a metal case with an ARM Cortex-M3 (STM32F205). When I try to use snprintf() with floating point numbers, for example:
float f; f = 1.23; snprintf(s, 20, "%5.2f", f);
I get garbage in s . The format seems to deserve attention, i.e. Trash is a well-formed string with numbers, a decimal point, and two trailing digits. However, if I repeat snprintf , the line may change between two calls.
Floating point math seems to work differently, and snprintf works with integers, like this:
snprintf(s, 20, "%10d", 1234567);
I am using the newlib-nano implementation with the -u _printf_float linker -u _printf_float . Compiler arm-none-eabi-gcc .
I have a strong suspicion of memory allocation problems, since integers are printed without any hiccups, but floating actions act as if they were damaged in the process. The printf family functions call malloc with floats, not integers.
The only piece of code that does not belong to newlib that I use in this context is my _sbrk() , which is required by malloc .
caddr_t _sbrk(int incr) { extern char _Heap_Begin; // Defined by the linker. extern char _Heap_Limit; // Defined by the linker. static char* current_heap_end; char* current_block_address; // first allocation if (current_heap_end == 0) current_heap_end = &_Heap_Begin; current_block_address = current_heap_end; // increment and align to 4-octet border incr = (incr + 3) & (~3); current_heap_end += incr; // Overflow? if (current_heap_end > &_Heap_Limit) { errno = ENOMEM; current_heap_end = current_block_address; return (caddr_t) - 1; } return (caddr_t)current_block_address; }
As far as I managed to track, this should work. Nobody seems to ever call it negative increments, but I guess this is due to the newlib malloc design. The only bit strange: the first call to _sbrk has a zero increment. (But it might just be malloc curiosity about the starting address of the heap.)
The stack should not collide with a heap, since for them about 60 kilobytes of RAM. The script compiler may be insane, but at least the heap and stack addresses seem correct.