Getting garbage values while implementing linked list using structs in C# (unsafe construct) -
i trying verify behavior reported 1 of friends, implemented singly linked list in c# using struct. since had use pointers used unsafe construct provided c#. set property allow unsafe code
in build tab of project properties make code compilable.
here complete code implementation:
public unsafe struct nodelist { public node* head; public node* current; public void addnode(int d) { node n = new node(); n.data = d; n.link = null; if (head == null) { head = current = &n; } else { (*current).link = &n; current = &n; } console.writeline(head->data); } public void traversenodes() { node* temp = head; while(temp != null) { console.writeline(temp -> data); temp= temp -> link; } } } public unsafe struct node { public int data; public node* link; } class program { private static void unsafedsimplementation() { var mylinkedlist = new nodelist(); mylinkedlist.addnode(2); mylinkedlist.addnode(4); mylinkedlist.traversenodes(); } static void main(string[] args) { unsafedsimplementation(); } }
errant observations:
- every time go inside
addnode
method , try print node data value first time 2 , second time 4. i'm wondering how come head changing when assign once while adding first node. - while traversing nodes - value of data first node 2243610 (this keeps changing on every run garbage) ,
system.nullrefernceexception
exception second node iteration. both nodes should print data correctly.
now behavior i'm getting may due mistake i've made in code or may obvious i'm using pointers managed world. need figure out.
allocate memory using native marshal.allochglobal
(which malloc in c)
using system; using system.collections.generic; using system.linq; using system.runtime.interopservices; using system.text; using system.threading.tasks; namespace linked_list { public unsafe class nodelist { public static node * head ; public void addnode(int d) { node* newnode = (node*)marshal.allochglobal(sizeof(node)).topointer(); newnode->data = d; newnode->link = null; node* temp; if (head == null) { head = newnode; } else { temp = head; head = newnode; newnode->link = temp; } console.writeline(head->data); } public void traversenodes() { node* temp = head; while (temp != null) { console.writeline(temp->data); temp = temp->link; } } } public unsafe struct node { public int data; public node* link; } unsafe class program { private static void unsafedsimplementation() { var mylinkedlist = new nodelist(); mylinkedlist.addnode(2); mylinkedlist.addnode(4); mylinkedlist.traversenodes(); } static void main(string[] args) { unsafedsimplementation(); } } }
note: need free memory using marshal.freehglobal
Comments
Post a Comment