我正在尝试使用以下字符串对我的解析器进行崩溃测试:
var theWholeUTF8 = new StringBuilder();
for (char code = Char.MinValue; code <= Char.MaxValue; code++)
{
theWholeUTF8.Append(code);
}
Run Code Online (Sandbox Code Playgroud)
但是,测试在构建字符串时崩溃并抛出OutOfMemoryException.我错过了什么?
xan*_*tos 11
问题是code溢出并返回0之后Char.MaxValue.然后for循环不会结束.
尝试
var theWholeUTF8 = new StringBuilder();
for (int code = Char.MinValue; code <= Char.MaxValue; code++)
{
theWholeUTF8.Append((char)code);
}
Run Code Online (Sandbox Code Playgroud)
说清楚......在某一点上
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!
Run Code Online (Sandbox Code Playgroud)
一种可能的解决方案是使用code更大的变量.另一种解决方案是
for (char code = Char.MinValue; code < Char.MaxValue; code++)
{
theWholeUTF8.Append(code);
}
theWholeUTF8.Append(Char.MaxValue);
Run Code Online (Sandbox Code Playgroud)
我们在哪里停止code == Char.MaxValue,我们手动添加Char.MaxValue.
其他解决方案,通过在添加之前移动支票获得:
char code = Char.MinValue;
while (true)
{
theWholeUTF8.Append(code);
if (code == Char.MaxValue)
{
break;
}
code++;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
303 次 |
| 最近记录: |