开发者

same address returned in C# struct pointer

I created a structure pointer, but each call for the new node returns the same address. But i expected different address to be returned for each invocation of the new node. Can someone please help?

public unsafe struct Node
{
    public int Data;
}
class TestPointer
{
    public uns开发者_如何学Goafe Node* getNode(int i)
    {
        Node n = new Node();
        n.Data = i;
        Node* ptr = &n;
        return ptr;
    }
    public unsafe static void Main(String[] args)
    {
        TestPointer test = new TestPointer();
        Node* ptr1 = test.getNode(1);
        Node* ptr2 = test.getNode(2);
        if (ptr1->Data == ptr2->Data)
        {
            throw new Exception("Why?");
        }
    }
}


Don't be fooled by the Node n = new Node(); syntax! Node being a struct, n is allocated on the stack. You call getNode twice from the same function in the same environment, so naturally you are getting two pointers to the same stack location. What's more these pointers become invalid ('dangling') once getNode returns, because the stack location that belonged to n may be overwritten by a different call. In short: don't do it. If you want CLR to allocate memory, make Node a class.


Is n getting garbage collected?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜