"FatalExecutionEngineError was detected" when using Console.Writeline after redefining String.Empty

2

I'm trying (for fun) to redefine String.Empty to be a single space "". Why does this break the CLR framework?

Message:

The runtime has encountered a fatal error. The address of the error was at 0x5814b976, on thread 0xf40. The error code is 0x80131623. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.

How to reproduce:

class Program
{
    static void Main()
    {
        typeof(string).GetField("Empty").SetValue(null, " ");
        Console.WriteLine("{}", "");
    }
}
c#
visual-studio-2010
clr
asked on Stack Overflow May 24, 2011 by Espo

1 Answer

2

If we look at the program

class Program
{
    static void Main()
    {
        Console.WriteLine("{}", "");
    }
}

then it will fail with an FormatException with the error message Input string was not in a correct format.

However when we insert typeof(string).GetField("Empty").SetValue(null, " "); before the line with Console.WriteLine then the code fails when it tries to look up that error message. If we look at the full stacktrace (including "Show external code") then we see that the code fails at System.Resources.ManifestBasedResourceGroveler.HandleResourceStreamMissing(string fileName = " mscorlib.resources") (notice the space in front of mscorlib.resources).

The reason for this is that ManifestBasedResourceGroveler uses the metode GetResourceFileName of ResourceManager to find the resource file. And in GetResourceFileName we use a StringBuilder to construct the filename and the constructor of StringBuilder starts with String.Empty.

public StringBuilder(int capacity)
    : this(String.Empty,capacity){
}
answered on Stack Overflow May 8, 2012 by Mikkelbu

User contributions licensed under CC BY-SA 3.0