Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 unsafe 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?");
        }
    }
}
like image 841
Thiyaneshwaran S Avatar asked Aug 22 '26 12:08

Thiyaneshwaran S


1 Answers

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.

like image 198
Anton Tykhyy Avatar answered Aug 24 '26 03:08

Anton Tykhyy