Fuzzy behavior of a fixed pointer outside of a fixed operator
Can someone explain to me why below C # code is not crashing? Why does Visual Studio really let you compile it? I understand that I am getting a fixed pointer, but it is only fixed in a "fixed" statement. When the pointer is returned from the "Foo" function, the ar array can be collected. Then I force the GC, but the sequential write to memory (which is now freed) does not throw any errors.
class Program
{
static unsafe byte* Foo()
{
byte[] ar = new byte[100];
fixed (byte* ptr = ar)
{
return ptr;
}
}
static unsafe void Main(string[] args)
{
byte* ptr = Foo();
GC.Collect();
for (int t = 0;;++t) ptr[t%100] = 0;
}
}
a source to share
Eric is right, but the answer you probably want to hear is that "it is sometimes useful to keep an address outside of a fixed operator."
Perhaps the memory from that pointer has already been fixed by another fixed statement somewhere else and it makes sense to return it? The compiler doesn't try to guess and give noisy warnings.
However, I hope that CodeAnalysis or other advanced tools will come in here where the compiler will allow you to cut off your leg.
Just because freed memory doesn't mean that writing to it will throw an error of any type. When the garbage collector reclaims memory, it simply marks it as free in its internal memory card - it doesn't bring it back to the OS right away, so it still saves memory for your process.
Of course, using a pointer outside of a fixed block for it is a very bad idea - don't do it.
a source to share