Question

I read an example from an older StackOverflow post about when to use stackalloc. Now this example has me a bit puzzled:

public unsafe void DoSomeStuff()
{
    byte* unmanaged = stackalloc byte[100];
    byte[] managed = new byte[100];

    //Do stuff with the arrays

    //When this method exits, the unmanaged array gets immediately destroyed.
    //The managed array no longer has any handles to it, so it will get 
    //cleaned up the next time the garbage collector runs.
    //In the mean-time, it is still consuming memory and adding to the list of crap
    //the garbage collector needs to keep track of. If you're doing XNA dev on the
    //Xbox 360, this can be especially bad.
}

Now feel free to correct me if I'm wrong, as I'm still quite a novice in C# and programming in general. But aren't bytes value types? And aren't value types stored where they are declared? Doesn't this mean that in this example, managed is also stored on the stack, and by extension when this stack frame finishes and it goes to the calling adress the memory is cleaned up automatically and therefore managed should be removed in the same manner as unmanaged in this example?

Was it helpful?

Solution 2

Isolated bytes are indeed value types, but arrays are reference type. The pointer to managed here is stored on the stack, same as the entire unmanaged variable, but the memory consumed by the array isn't reclaimed until the garbage collector runs.

OTHER TIPS

The type byte[] looks similar to stackalloc byte[100], but it represents something completely different. A byte[] holds a reference to an instance of a heap object whose type derives from System.Array, while a stackalloc byte[100] (and, for that matter a fixed byte[100];) holds 100 bytes. Code which expects something of type byte[] will only accept a heap object reference; it will not accept 100 bytes directly. As with all reference types, a System.Array instance to which any sort of reference exists is guaranteed to exist for as long as the reference itself does (if an object is discovered to be accessible only via weak references, those references will be invalidated before the object ceases to exist, so as to uphold this invariant). If no reference to the array is stored anywhere outside the current stack frame, it will cease to exist after the stack frame exits, but if a reference is stored somewhere else, the array will survive as long as any reference does.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top