I have a block of code below with a single line commented out. What happens in the CreateArray method is the same thing that the commented out line does. My question is why does it work when the line b->ArrayItems = d is uncommented, but return garbage when commented out? I don’t think I have to “fixed” anything, because all of the information is unmanaged. Is this assumption incorrect?
class Program
{
unsafe static void Main(string[] args)
{
someInstance* b = stackalloc someInstance[1];
someInstance* d = stackalloc someInstance[8];
b->CreateArray();
// b->ArrayItems = d;
*(b->ArrayItems)++ = new someInstance() { IntConstant = 5 };
*(b->ArrayItems)++ = new someInstance() { IntConstant = 6 };
Console.WriteLine((b)->ArrayItems->IntConstant);
Console.WriteLine(((b)->ArrayItems - 1)->IntConstant);
Console.WriteLine(((b)->ArrayItems - 2)->IntConstant);
Console.Read();
}
}
public unsafe struct someInstance
{
public someInstance* ArrayItems;
public int IntConstant;
public void CreateArray()
{
someInstance* d = stackalloc someInstance[8];
ArrayItems = d;
}
}
The commented line is what is masking the bug caused by CreateArray. Commenting it out exposes the bug. But the bug is there regardless.
As the specification clearly states:
The CreateArray function allocates a block, you store a pointer to the block, the block is discarded, and now you have a pointer to a garbage block. You are required to never store a pointer to a stackalloc’d block such that the storage can be accessed after the block becomes invalid. Heap allocate the block if you need to store a reference to it, and remember to deallocate it when you’re done.
Remember, in unsafe code you are required to fully understand everything about the managed memory model. Everything. If you don’t understand everything about managed memory, don’t write unsafe code.
That said, let’s address what seems to be your larger confusion, which is “when do you have to fix memory to obtain a pointer?” The answer is simple. You have to fix memory if and only if it is movable memory. Fixing transforms movable memory into immovable memory; that’s what fixing is for.
You can only take the address of something that is immovable; if you take the address of something that is movable and it moves then obviously the address is wrong. You are required to ensure that memory will not move before you take its address, and you are required to ensure that you do not use the address after it becomes movable again.