CountMurphy
CountMurphy

Reputation: 1096

snprintf printing giberish on microcontroller, but is fine in other environments

I am trying to simply convert a double to a string in C. Running


char printable[9];

snprintf(printable, 9, "%f", 30.356145);

should set printable to "30.35614". When I run this code on an online c compiler it outputs correctly. When I output it on my Microcontroller printable equals this nonsense:

"\000\033\000\000\001\000\000\000\024"
  1. Why is am I getting this this garbage data?
  2. What is this garbage data?
  3. How can I get snprintf to function properly?

Upvotes: 0

Views: 256

Answers (1)

Maximilian Gerhardt
Maximilian Gerhardt

Reputation: 5353

From the output it could be seen that snprintf immediately terminated the string with \0 character and left the rest untouched. Since the array was allocated on the stack and not zero-initialized, the rest of the array values are indeterminate.

As it was confirmed by @CountMurphy's comment, the problem was that the C-library newlib-nano was used.

On microcontrollers Flash is precious and printf and related functions are one of the biggest functions in the library. Thus on embedded microcontrollers, we tend to strip out unnecessary things like float and double format specifier handling code.

The issue is resolved by explicitly activating floating-point printf support in newlib-nano, as it is instructed in the official resource here and here. One way to activate support is to add the linker flag

-u _printf_float

To the final arm-none-eabi-gcc command. This will force the inclusion of the symbol / function _printf_float which subsequently makes the %f format specifier work as expected.

Upvotes: 7

Related Questions