为什么StreamReader.ReadLine抛出OutOfMemoryException异常?抛出、异常、StreamReader、ReadLine

2023-09-03 05:01:42 作者:可遇不可求

谁能告诉我,为什么在最后一个线在这里抛出OOM异常?

 字节[]缓冲区=新的字节[1];
        缓冲液[0] = 239;
        MemoryStream的毫秒=新的MemoryStream(缓冲);
        StreamReader的SR =新的StreamReader(MS);
        串L1 = sr.ReadLine();
        串12 = sr.ReadLine();
 

解决方案

恭喜你,你已经找到了在.NET框架中的错误。它是由字节值诱导,0xef十六进制。这是 UTF-8 BOM 的第一个字节。这当然不是一个完整的BOM,接下来的两个字节丢失。然而足以致命混淆的StreamReader,它不断努力而没有得到任何地方,消耗内存,而试图读取数据流。 OOM是,最终,下一个。

这个错误是present在.NET 4.0中为好。这个bug的确切来源很难追查,都涉及了code未包含在参考源。它可能被分类为关键的,因为它可以在DOS攻击中使用。您可以在connect.microsoft.com报告的bug。让我知道如果你不想要,我会报告它(MVP税)。

关于JVM内存溢出的原因分析及解决方案探讨

Can anyone tell me why the last line here throws OOM exception?

        byte[] buffer = new byte[1];
        buffer[0] = 239;
        MemoryStream ms = new MemoryStream(buffer);
        StreamReader sr = new StreamReader(ms);
        string l1 = sr.ReadLine();
        string l2 = sr.ReadLine();

解决方案

Congratulations, you've found a bug in the .NET framework. It is induced by the byte value, 0xef in hex. Which is the first byte of the UTF-8 BOM. It is not a complete BOM of course, the next two bytes are missing. It is however enough to fatally confuse StreamReader, it keeps trying to read data from the stream without ever getting anywhere, consuming memory while trying. OOM is, eventually, next.

This bug is present in .NET 4.0 as well. The exact source of the bug is hard to trace, the code that's involved is not included in the Reference Source. It could possibly be classified as a critical one since it could be used in a DOS attack. You can report the bug at connect.microsoft.com. Let me know if you don't want to, I'll report it (MVP duty).