次の文字列を使用してパーサーをクラッシュ テストしようとしています。
var theWholeUTF8 = new StringBuilder();
for (char code = Char.MinValue; code <= Char.MaxValue; code++)
{
theWholeUTF8.Append(code);
}
ただし、文字列の構築中にテスト自体がクラッシュし、OutOfMemoryException がスローされます。私は何が欠けていますか?
問題は、オーバーフローして になった後に にcode
戻ることです。その後、サイクルは終了しません。0
Char.MaxValue
for
試す
var theWholeUTF8 = new StringBuilder();
for (int code = Char.MinValue; code <= Char.MaxValue; code++)
{
theWholeUTF8.Append((char)code);
}
明確にするために... ある時点で
code = Char.MaxValue - 1
code++; // code == Char.MaxValue
is code <= Char.MaxValue? Yes
theWholeUTF8.Append((char)code);
code++; // code == 0
is code <= Char.MaxValue? Yes
theWholeUTF8.Append((char)code);
and so on!
code
考えられる解決策の 1 つは、より大きな変数を使用することです。別の解決策は次のとおりです。
for (char code = Char.MinValue; code < Char.MaxValue; code++)
{
theWholeUTF8.Append(code);
}
theWholeUTF8.Append(Char.MaxValue);
いつ停止しcode == Char.MaxValue
、手動でChar.MaxValue
.
追加の前にチェックを移動することによって得られる他の解決策:
char code = Char.MinValue;
while (true)
{
theWholeUTF8.Append(code);
if (code == Char.MaxValue)
{
break;
}
code++;
}