views:

110

answers:

1

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();
+5  A: 

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).

Hans Passant
Opened bug #594588
skb
Upvoted. URL: http://connect.microsoft.com/VisualStudio/feedback/details/594588/why-does-streamreader-readline-throw-outofmemoryexception
Hans Passant