c - 串行端口 IAR 上的 Sprintf 和浮点值

标签 c floating-point

我正在 IAR 工作台上编译以下代码片段。

// global declaration
float fval = 3.14f;
uint8_t uartTxBuffer [100];

void function(void)
{
  memset(uartTxBuffer,'\0',sizeof(uartTxBuffer);
  sprintf(uartTxBuffer,"\n\r Value is %f",fval);
  UartWrite(uart, uartTxBuffer,strlen(uartTxBuffer));
}

输出是 值为 %f//而不是 3.14 有人可以解释一下我的代码有什么问题吗? 是Uartwrite函数的问题还是我在使用C语言时犯了一些错误? 我在 Keil MDK 上使用 printf 尝试了相同的代码,它在串行终端上输出了正确的值。那么这是一个 IDE 问题吗? 有人可以指导我吗?

最佳答案

经过简短的研究后出现了这个问题

https://www.iar.com/support/tech-notes/general/problems-with-printf-floating-point-f-on-arm/

问题似乎是堆栈指针的字节对齐。 在 sprintf() 调用上设置断点并检查调试器中堆栈指针的值。

我找到的大多数答案都与FreeRTOS有关(我不知道你是否使用它):

sprintf breaking under new FreeRTOS

sprintf %f corrupts stack

sprintf in FreeRTOS

常见的解决方案是诉诸

a third party library called printf-stdarg.c that provides a tiny print/sprintf/printf implementation for use in cases where the libraries that come with the compiler are just too big for small embedded use

希望这会有所帮助

关于c - 串行端口 IAR 上的 Sprintf 和浮点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55113042/

相关文章:

在此代码中转换像素

c++ - openCV/图像处理中创建 MAT 类型的 3 维数组时出现段错误

c - Format String 漏洞困扰

c# - 在 C# 中将字符串数组转换为 float 组

c - 无索引的指针算法的双指针内存分配访问问题

c - 访问结构指针数组时出错

c++ - 答案怎么是-0?

floating-point - 浮点乘法与加法的计算成本是多少?

javascript - 比较两个 float 以查看它们是否均为负数或均为正数

c# - 将尾数和指数转换为 double