【问题标题】:StringBuilder out of memoryStringBuilder 内存不足
【发布时间】:2013-08-11 20:10:49
【问题描述】:

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

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

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

【问题讨论】:

  • theWholeUTF8 并不是一个准确的变量名; UTF-8 是一种编码,.NET 字符串使用 UTF-16。
  • @minitech 感谢您的提示!
  • 另外,该字符串实际上不是有效的 UTF-16。而且它不会包含所有 Unicode 代码点。
  • @MikeRoll 因为surrogate pairs

标签: c# string


【解决方案1】:

问题是code 溢出并在成为Char.MaxValue 之后返回到0for 循环不会结束。

试试

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++;
}

【讨论】:

  • 啊哈就是这样!或者使用char &lt; Char.MaxValue 而不是char &lt;= Char.MaxValue。它永远不能大于它的最大值:)
  • @AlexMDC 但是他会丢失 Char.MaxValue “值”,他必须手动添加它。
  • 好点。如果您尝试“崩溃测试”一段代码,这一点很重要。
猜你喜欢
  • 2013-11-01
  • 1970-01-01
  • 2016-06-09
  • 1970-01-01
  • 2011-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-11
相关资源
最近更新 更多