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) { /* success */ } else { /* error */ };
しかし、 を含むコマンド バッファで呼び出すと、コマンドに2 つの引数しか指定されていない場合でも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;