views:

107

answers:

4

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 dont 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;
    }
}
+1  A: 

Oddly, I would have expected it to return garbage when not commented; doesn't CreateArray end up storing a pointer to the stack? Which will be invalid after CreateArray exits...

Marc Gravell
I think everyone else, including me, read it wrong. But you're right, the question says it works when uncommented. Maybe it's just a typo...
Martin
@Martin - quite probably I'm focusing more on `CreateArray`, since that is the one that struck me as odd... but the "commented" is the line below this. Maybe this accidentally fixes it ;p
Marc Gravell
+8  A: 

My question is why does it work when the line is uncommented, but return garbage when commented out.

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:

All stack allocated memory blocks created during the execution of a function member are automatically discarded when that function member returns.

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.

Eric Lippert
That's a trap: if you don't start playing around and make mistakes, you'll never learn to understand everything of the managed memory model, but if you must first understand everything before you start playing unsafely...
Abel
"never store a pointer to..." is arguably a bit strong? Surely you *can* store it as long as you ensure that that storage lasts no longer than the stack-allocated block.
Marc Gravell
@Marc: Sure, I take your point. By "store" I meant to imply something *persistent* beyond the current scope.
Eric Lippert
@Eric - cheers. Oddly enough, despite lots of messing around in some truly *insane* `ILGenerator` code involving stack *torture*, `stackalloc` (and the IL counterpart) is something I have had to use (in production code) precisely *never*.
Marc Gravell
Eric, when you say "Heap allocate the block if you need to store a reference to it", can you go into exactly what that would entail?
Dested
@Dested: Either allocate it off the managed heap by making an array and then fixing it in place, or allocate it off the unmanaged heap via any unmanaged allocator you like. I believe the Marshal class has a bunch of unmanaged memory allocators. You are then required to (1) unfix or free the memory when you're done with it, and (2) not keep a pointer around after the unfix/free operation. Remember, *you are required to correctly access the memory.* By turning the safety system off you get to be in charge of everything that the memory model is normally in charge of.
Eric Lippert
You the man, Eric.
Dested
+1  A: 

Stackalloc allocates some space on the callstack, that space is then lost when you move up out of the current level of context (for example, leaving a method). You're problem is that when the stackalloc is inside a method then that area of the stack is no longer yours to play with when you leave that method.

So, if you do this:

foo()
{
    stuff = stackalloc byte[1]
    Do something with stuff
}

"stuff" is only valid inside foo, once you leave foo the stack is wound back, which means that if you do this:

foo()
{
    byte* allocate()
    {
        return stackalloc[1]
    }

    stuff = allocate()
    do something with stuff
}

then the return value of allocate becomes rubbish when you leave the allocate method, which means that "stuff" never makes any sense.

Martin
+1  A: 

Your assumption is partially correct, but understood incorrectly. Here's a quote from this MSDN page:

In unsafe mode, you can allocate memory on the stack, where it is not subject to garbage collection and therefore does not need to be pinned. See stackalloc for more information.

Some statements will allocate variables on the stack automatically (i.e., value types inside a method), others will need to be specified specifically using stackalloc.

Stack allocated memory is discarded after the method ends, hence your issue (see Eric Lipperts answer, who wrote this before me).

Abel