The confusion is whether to use fixed with unsafe code and stackalloc

I have a block of code below with one line commented out. What happens in the method CreateArrayis the same as in the numbered line. My question is why it works when the line is b->ArrayItems = duncommented, but return garbage when commenting? I don’t think that I need to “fix” anything because all the information is uncontrollable. Is this assumption wrong?

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;
    }
}
+3
source share
3 answers

My question is why it works when the line is uncommented, but return garbage when commenting.

- , , CreateArray. , . .

:

, , , , .

CreateArray , , , . stackalloc'd, , . , , , .

, . . , .

, , , " , ?" . , . ; .

-, ; , , , , . , , , , , .

+13

Stackalloc , , (, ). , stackalloc , , .

, :

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

"" foo, foo, , , :

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

    stuff = allocate()
    do something with stuff
}

allocate , allocate, , "" .

+1

, . MSDN:

, . . stackalloc.

(.. ), stackalloc.

The deferred stack memory will be discarded after the method completes, hence your problem (see Eric Lipperts), who wrote this in front of me.

+1
source

Source: https://habr.com/ru/post/1756653/


All Articles