我们使用sscanf()
eCos操作系统下的函数来解析用户提供的命令行命令。我们有基本上可以做到这一点的代码:
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 */ };
但是当使用包含 的命令缓冲区调用时command arg1 40.0
,success
即使只为命令提供了两个参数,也会进入分支。我们本来期望error
分支会被执行。
使用大量printf()
语句,以下是调用后的变量值sscanf()
:
buffer = "command arg1 40.0"
arg1 = "arg1"
arg2 = 40.0
arg3 = ""
我们无法通过单元测试重现此行为。在我们开始怀疑一个被破坏的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;