1

我正在尝试使用以下字符串对我的解析器进行崩溃测试:

var theWholeUTF8 = new StringBuilder();
for (char code = Char.MinValue; code <= Char.MaxValue; code++)
{
        theWholeUTF8.Append(code);
}

但是,测试在构建字符串时会自行崩溃并抛出 OutOfMemoryException。我错过了什么?

4

1 回答 1

11

问题是 tha溢出并在 be之后code返回。然后循环不会结束。0Char.MaxValuefor

尝试

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更大的变量。另一种解决方案是:

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++;
}
于 2013-08-11T20:12:26.157 回答