Recursive struct definitions in Solidity (Creating Linked Lists) - recursion

I'm trained mostly in Java so this has never really been an issue for me, but I'm trying to create a linked list in Solidity for a smart contract I am working on. In it, I am using a struct written as such:
struct Node {
address addr;
Node _next;
Node prev;
}
While I'm still working out the kinks on whether it's worth it to keep it as a single or doubly linked list, the main issue is that I have a recursive struct definition problem by referencing a Node struct inside my Node struct. I am a little unsure of what my alternatives are. Is this just a limitation of the language? I read this thread, but I couldn't really tell if the answer given was anything more than "it depends".
Thanks for any feedback; let me know if I can provide more information.

You could do it like this (double linked list):
pragma solidity ^0.4.24;
contract LinkedList {
struct Node {
string data;
uint pointPrevNode;
uint pointNextNode;
}
mapping(uint => Node) public nodes;
uint public nodeNumber = 0;
uint public count = 1;
function setData(string _data) public {
nodes[count].data = _data;
assignPointers(count);
}
function assignPointers(uint _count) internal {
nodes[nodeNumber].pointNextNode = _count;
nodes[_count].pointPrevNode = nodeNumber;
nodeNumber = _count;
count++;
}
}

Related

Is `R_ClearExternalPtr()` needed to finalize an external pointer object in R?

While reading Writing R Extensions, Section 5.13 External pointers and weak references we see an example of a finalizer using R_ClearExternalPtr() albeit the comment next to it saying not really needed:
(...) The finalizer code is simply
static void chanFinalizer(SEXP ptr)
{
if(!R_ExternalPtrAddr(ptr)) return;
inRODBCClose(R_ExternalPtrAddr(ptr));
R_ClearExternalPtr(ptr); /* not really needed */
}
In the post Storing C objects in R by #Martin-Morgan he provides two finalizer examples, where he does include a call to R_ClearExternalPtr() in the first case but not in the second:
First example:
static void
_finalizer(SEXP ext)
{
if (NULL == R_ExternalPtrAddr(ext))
return;
Rprintf("finalizing\n");
char *ptr = (char *) R_ExternalPtrAddr(ext);
Free(ptr);
R_ClearExternalPtr(ext);
}
Second example:
static void
_finalizer(SEXP ext)
{
struct Foo *ptr = (struct Foo*) R_ExternalPtrAddr(ext);
Free(ptr);
}
Can someone help clarify the comment not really needed, and whether I should call R_ClearExternalPtr() at the end of the finalizer.

MQL4/5 CList Search method always returning null pointer

I'm trying to use the CList Search method in an application. I have attached a very simple example below.
In this example, I always get a null pointer in the variable result. I tried it in MQL4 and MQL5. Has anyone ever made the Search method work? If so, where is my mistake? With my question, I refer to this implementation of a linked list in MQL (it's the standard implementation). Of course, in my application, I do not want to find the first list item, but items that match specific criteria. But even this trivial example does not work for me.
#property strict
#include <Arrays\List.mqh>
#include <Object.mqh>
class MyType : public CObject {
private:
int val;
public:
MyType(int val);
int GetVal(void);
};
MyType::MyType(int val): val(val) {}
int MyType::GetVal(void) {
return val;
}
void OnStart() {
CList *list = new CList();
list.Add(new MyType(3));
// This returns a valid pointer with
// the correct value
MyType* first = list.GetFirstNode();
// This always returns NULL, even though the list
// contains its first element
MyType* result = list.Search(first);
delete list;
}
CList is a kind of linked list. A classical arraylist is CArrayObj in MQL4/5 with Search() and some other methods. You have to sort the list (so implement virtual int Compare(const CObject *node,const int mode=0) const method) before calling search.
virtual int MyType::Compare(const CObject *node,const int mode=0) const {
MyType *another=(MyType*)node;
return this.val-another.GetVal();
}
void OnStart(){
CArrayObj list=new CArrayObj();
list.Add(new MyType(3));
list.Add(new MyType(4));
list.Sort();
MyType *obj3=new MyType(3), *obj2=new MyType(2);
int index3=list.Search(obj3);//found, 0
int index2=list.Search(obj2);//not found, -1
delete(obj3);
delete(obj2);
}

C# Marshal byte array to struct

I find many answers to my question and they all work. My question is are they all equal in speed and memory. How can I tell what is faster and uses less memory. I don't normally use the Marshal and GCHandle classes. So I am totally green.
public static object RawDeserializer(byte[] rawData, int position, Type anyType)
{
int rawsize = Marshal.SizeOf(anyType);
if (rawsize > rawData.Length)
return null;
IntPtr buffer = Marshal.AllocHGlobal(rawsize);
Marshal.Copy(rawData, position, buffer, rawsize);
object retobj = Marshal.PtrToStructure(buffer, anyType);
Marshal.FreeHGlobal(buffer);
return retobj;
}
public static T RawDeserializer<T>(byte[] rawData, int position = 0)
{
int rawsize = Marshal.SizeOf(typeof(T));
if (rawsize > rawData.Length)
{
throw new DataMisalignedException("byte array is not the correct size for the requested type");
}
IntPtr buffer = Marshal.AllocHGlobal(rawsize);
Marshal.Copy(rawData, position, buffer, rawsize);
T retobj = (T)Marshal.PtrToStructure(buffer, typeof(T));
Marshal.FreeHGlobal(buffer);
return retobj;
}
public static T RawDeserializer<T>(byte[] bytes) where T : struct
{
T stuff;
GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
try
{
stuff = Marshal.PtrToStructure<T>(handle.AddrOfPinnedObject());
}
finally
{
handle.Free();
}
return stuff;
}
I am getting the desired results form all 3 implementations.
First and second are almost identical: difference is that you do not unbox (cast to T:struct) the result in the first example, I'd assume that you'll unbox it later though.
Third option does not copy memory to the unmanaged heap, it just pins it in manageed heap, so I'd assume it will allocate less memory and will be faster. I don't pretend to be a golden source of truth though, so just go and make performance testing of these options :) BenchmarkDotNet is a great framework for performance testing and may help you a lot.
Also third option could be more concise:
public static unsafe T RawDeserializer<T>(byte[] bytes) where T : struct
{
fixed (byte* p = bytes)
return Marshal.PtrToStructure<T>((IntPtr)p);
}
You need to change project settings to allow unsafe code though:
To do not be totally green, I'd strongly recommend to read a book CLR via C#, Chapter 21 'The Managed Heap and Garbage Collection'.

Rebuild BST from preorder, error in logic

Trying to wrap my head around how to correct my code. I have the idea up, but I get stuck during the implementation.
when I step through the code below, I can reconstruct part of the BST from a pre-order traversal. But at some point, I will have function call like:
recon(preOrd,2,2)
which results in a leaf not being assigned. I do yet know how to correct this.
I have seen other threads on this topic, but want to iron out my issue so I can really learn this concept of rebuilding the BST.
public static Node recon(int[] preOrd,int start,int end){
if (start==end){
return null;
}
Node root = new Node (preOrd[start]);
int div=start;
for (i=start+1;i<=end && preOrd[i]<preOrd[start];i++){
div=i;
}
Node left= reconstruct(preOrd,start+1,div);
Node right= reconstruct(preOrd,div+1,end);
root.setLeft= left;
root.setRight=right;
return root;
}
Turns out this is pretty straightforward. Just needed to correct my thinking on the updating of leaf nodes..
public static Node recon(int[] preOrd,int start,int end){
Node root = new Node (preOrd[start]);//declare the new node
if (start>end){ //this is illegal, so return null
return null;
}
if (start==end){
return root;
}
int div=start;
for (int i=start+1;i<=end preOrd[i]<preOrd[start];i++){
div=i;
}
Node left= reconstruct(preOrd,start+1,div);
Node right= reconstruct(preOrd,div+1,end);
root.setLeft= left;
root.setRight=right;
return root;
}

segfault after return 0;

I wrote a program to test my binary tree and when I run it, the program seems to crash (btree.exe has stopped working, Windows is checking for a solution ...).
When I ran it through my debugger and placed the breakpoint on the function I suspect is causing it, destroy_tree(), it seemed to run as expected and returned back to the main function. Main, in turn, returned from the program but then the cursor jumped back to destroy_tree() and looped recusively within itself.
The minimal code sample is below so it can be ran instantly. My compiler is MinGW and my debugger is gdb (I'm using Code::Blocks).
#include <iostream>
using namespace std;
struct node
{
int key_value;
node *left;
node *right;
};
class Btree
{
public:
Btree();
~Btree();
void insert(int key);
void destroy_tree();
private:
node *root;
void destroy_tree(node *leaf);
void insert(int key, node *leaf);
};
Btree::Btree()
{
root = NULL;
}
Btree::~Btree()
{
destroy_tree();
}
void Btree::destroy_tree()
{
destroy_tree(root);
cout<<"tree destroyed\n"<<endl;
}
void Btree::destroy_tree(node *leaf)
{
if(leaf!=NULL)
{
destroy_tree(leaf->left);
destroy_tree(leaf->right);
delete leaf;
}
}
void Btree::insert(int key, node *leaf)
{
if(key < leaf->key_value)
{
if(leaf->left!=NULL)
insert(key, leaf->left);
else
{
leaf->left = new node;
leaf->left->key_value = key;
leaf->left->left = NULL;
leaf->left->right = NULL;
}
}
else if (key >= leaf->key_value)
{
if(leaf->right!=NULL)
insert(key, leaf->right);
else
{
leaf->right = new node;
leaf->right->key_value = key;
leaf->right->left = NULL;
leaf->right->right = NULL;
}
}
}
void Btree::insert(int key)
{
if(root!=NULL)
{
insert(key, root);
}
else
{
root = new node;
root->key_value = key;
root->left = NULL;
root->right = NULL;
}
}
int main()
{
Btree tree;
int i;
tree.insert(1);
tree.destroy_tree();
return 0;
}
As an aside, I'm planning to switch from Code::Blocks built-in debugger to DDD for debugging these problems. I heard DDD can display visually pointers to objects instead of just displaying the pointer's address. Do you think making the switch will help with solving these types of problems (data structure and algorithm problems)?
Your destroy_tree() is called twice, you call it once and then it gets called after the execution leaves main() from the destructor.
You may think it should work anyway, because you check whether leaf!=NULL, but delete does not set the pointer to NULL. So your root is not NULL when destroy_tree() is called for the second time,
Not directly related (or maybe it is) to your problem, but it's good practice to give structs a constructor. For example:
struct node
{
int key_value;
node *left;
node *right;
node( int val ) : key_val( val ), left(NULL), right(NULL) {}
};
If you do this, your code becomes simpler, because you don't need worry about setting the pointers when you create a node, and it is not possible to forget to initialise them.
Regarding DDD, it;'s a fine debugger, but frankly the secret of debugging is to write correct code in the first place, so you don't have to do it. C++ gives you a lot of help in this direction (like the use of constructors), but you have to understand and use the facilities it provides.
Btree::destroy_tree doesn't set 'root' to 0 after successfully nuking the tree. As a result, the destructor class destroy_tree() again and you're trying to destroy already destroyed objects.
That'll be undefined behaviour then :).
Once you destroy the root.
Make sure it is NULL so it does not try to do it again (from the destructor)
void Btree::destroy_tree(node *leaf)
{
if(leaf!=NULL)
{
destroy_tree(leaf->left);
destroy_tree(leaf->right);
delete leaf;
leaf = NULL; // add this line
}
}

Resources