Skip to content

Memory corruption for newlib-nano with float printf and disabled heap #30055

@martinjaeger

Description

@martinjaeger

Describe the bug

We are facing a strange issue in our project based on STM32L072 with 20k of RAM. If certain features are enabled such that most of the RAM is consumed, float variables in printf statements (using newlib nano) get replaced by random junk characters. Printing of integers works fine. Also printk with recently added float support (cbprintf) works fine.

Example code:

printf("Junk: %.2f and maybe not: %d\n", 123.4F, 1234);

Results in:

Junk: <0xb0>@<break>
. <0x9d> and maybe not: 1234

To Reproduce

Haven't been able to generate a minimum working example to reproduce the issue, as it disappears if too much of the code is removed. However, it does not seem to be an issue in the application firmware itself. The issue happens in different threads and stack usage is still quite low (because I put all threads immediately into k_sleep(K_FOREVER) to exclude possible application firmware bugs):

I: Thread analyze:
I:  thread_analyzer     : unused 80 usage 432 / 512 (84 %)
I:  serial_thread_id    : unused 1160 usage 120 / 1280 (9 %)
I:  leds_thread         : unused 104 usage 152 / 256 (59 %)
I:  gsm                 : unused 1208 usage 216 / 1424 (15 %)
I:  control_thread_id   : unused 912 usage 112 / 1024 (10 %)
I:  idle 00             : unused 188 usage 68 / 256 (26 %)
I:  main                : unused 792 usage 232 / 1024 (22 %)

Possible root cause and workaround

Our application doesn't use the heap. Since PR #28486, the RAM reserved for the heap seems to be garbage-collected away in that case (independent of the value of CONFIG_HEAP_MEM_POOL_SIZE) and can be reused for the stack.

However, newlib requires malloc if printf is used with %f: http://www.nadler.com/embedded/newlibAndFreeRTOS.html

If I add a line void *mem_test = k_malloc(4); to the code, Zephyr compiles in the heap management again and the issue is gone.

I'm not 100% sure if the above is really the root cause or if it made the issue disappear by coincidence, but it looks plausible to me. Maybe someone with more insight into newlib internals can confirm.

This link posted by @pabigot on Slack might also be relevant: https://stackoverflow.com/questions/28746062/snprintf-prints-garbage-floats-with-newlib-nano

Ping @nashif @dcpleung @andrewboie @carlescufi as you were involved in mentioned PR.

Metadata

Metadata

Assignees

Labels

area: C LibraryC Standard LibrarybugThe issue is a bug, or the PR is fixing a bugpriority: mediumMedium impact/importance bug

Type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions