Embedded 为什么对sscanf()的调用与一个参数匹配得太多?
我们使用eCos操作系统下的Embedded 为什么对sscanf()的调用与一个参数匹配得太多?,embedded,scanf,ecos,Embedded,Scanf,Ecos,我们使用eCos操作系统下的sscanf()函数来解析用户提供的命令行命令。我们的代码基本上可以做到这一点: char[20] arg1 = ""; float arg2; char[20] arg3 = ""; int n = sscanf(buffer + offset, "%4s %f %3s", arg1, &arg2, arg3); // offset is length of command plus 1 for the space if (n == 3) { /* succ
sscanf()
函数来解析用户提供的命令行命令。我们的代码基本上可以做到这一点:
char[20] arg1 = "";
float arg2;
char[20] arg3 = "";
int n = sscanf(buffer + offset, "%4s %f %3s", arg1, &arg2, arg3); // offset is length of command plus 1 for the space
if (n == 3) { /* success */ } else { /* error */ };
但是当使用包含命令arg1 40.0
的命令缓冲区调用时,即使只为命令提供了两个参数,也会输入成功
分支。我们希望执行错误
分支
使用大量的printf()
语句,下面是调用sscanf()
后的变量值:
我们无法通过单元测试重现这种行为。在我们开始怀疑一个坏的sscanf()
实现之前,还有其他解释吗
更新
eCos操作系统实现了自己版本的C标准库。下面是处理%s
格式说明符的代码片段。我不知道这是否有帮助,但我们越来越有信心这里可能有一个错误
139 #define CT_STRING 2 /* %s conversion */
....
487 switch (c)
....
597 case CT_STRING:
598 /* like CCL, but zero-length string OK, & no NOSKIP */
599 if (width == 0)
600 width = ~0;
601 if (flags & SUPPRESS)
602 {
603 n = 0;
604 while (!isspace (*CURR_POS))
605 {
606 n++, INC_CURR_POS;
607 if (--width == 0)
608 break;
609 if (BufferEmpty)
610 break;
611 }
612 nread += n;
613 }
614 else
615 {
616 p0 = p = va_arg (ap, char *);
617 while (!isspace (*CURR_POS))
618 {
619 *p++ = *CURR_POS;
620 INC_CURR_POS;
621 if (--width == 0)
622 break;
623 if (BufferEmpty)
624 break;
625 }
626 *p = 0;
627 nread += p - p0;
628 nassigned++;
629 }
630 continue;
“我们无法通过单元测试重现此行为。”我也无法重现此错误,即使在输入字符串中的参数后面有一个有希望的尾随换行符(尽管不使用eCos)。请提供一份演示问题的MCVE。还可以打印f()偏移量的值吗?
139 #define CT_STRING 2 /* %s conversion */
....
487 switch (c)
....
597 case CT_STRING:
598 /* like CCL, but zero-length string OK, & no NOSKIP */
599 if (width == 0)
600 width = ~0;
601 if (flags & SUPPRESS)
602 {
603 n = 0;
604 while (!isspace (*CURR_POS))
605 {
606 n++, INC_CURR_POS;
607 if (--width == 0)
608 break;
609 if (BufferEmpty)
610 break;
611 }
612 nread += n;
613 }
614 else
615 {
616 p0 = p = va_arg (ap, char *);
617 while (!isspace (*CURR_POS))
618 {
619 *p++ = *CURR_POS;
620 INC_CURR_POS;
621 if (--width == 0)
622 break;
623 if (BufferEmpty)
624 break;
625 }
626 *p = 0;
627 nread += p - p0;
628 nassigned++;
629 }
630 continue;