tags:

views:

161

answers:

2

Ok, this is a weird one. The junk data isn't random either, it appears to be substrings of the executable itself.

private void Form1_Load(object sender, EventArgs e)
{
    string s = GetValue();
    // at this point, s == "400". Why isn't really relevant (dumbed down a test)
    if (s != "18446744073709551615") 
        throw new Exception();
        // When the exception is thrown though, the string is set to random
        // data from inside the executable.
}

This seems dependant on certain seemingly insignificant implementation details in GetValue() such as calls to string.Format() being in different places.

Has anyone ever run into something similar or have any ideas what might cause this?

A: 

If you're checking the variable after the exception has been thrown and is now out of scope, then it should be pointing to nothing more than garbage sitting in memory. Have you tried checking the value of this variable both before and after the exception has been thrown?

Ryan Taylor
This seems to be the case... But why does it only seem to happen with a string? If I have an integer with the same scope I can see the value of it fine in the "Locals" windows.
Matthew Scharley
+1  A: 

"And I'm checking it in the "Locals" window in VS"

That explains it. Contrary to popular belief, C# is allowed to do some amount of optimization. If you don't add a "KeepAlive" at the end of your function, the value doesn't really have to be stored.

Windows programmer
Same question to you as Ryan then: why does an integer declared at the start of the function not disappear along with the exception like the string does?
Matthew Scharley
How do you know if it disappeared or not? It occupied less space in a different location so it's just less likely to have been stepped on yet.
Windows programmer
Um, also since this is C#, the int is a value type and the string is a reference type.
Windows programmer