Question

I have a tree structure that i am creating the following way. The tree is created correctly as far as i know. But when i want to get the data from a node, i get some weird acsii symbols.

How I set the data.Lets say its empty. Doesn't matter at the moment. I have a value in my program. The function feeds itself until i get to the end of the data.

struct Node {
    char Data;
    Node* Left;
    Node* Right;
};

Node maketree(0,s,split)
{
    Node node;
    node.Data=' ';

    Node n1=subsplit(0,s,splitingat);
    Node n2= subsplit(1,splitingat+1,e);
    node.Left=&n1;
    node.Right=&n2;

    return node; 
 }

This is how i get data from the tree.

char decode(Node node,string text)
{
    int currentindex=0;
    Node sub=node;
    {
    }
    if(text[currentindex]=='0')
    {
        sub=*sub.Left;
        cout<<" x "<<sub.Data<<endl;
    }
    else if(text[currentindex]=='1')
    {
        sub=*sub.Right;
        cout<<" x "<<sub.Data<<endl;
    }

   // cout<<sub.Data<<endl;
}

I think that the mistake is that I am printing out the pointer and not the node. But I don't know where I went wrong.

Was it helpful?

Solution

The source of your problem appears to be here:

Node node;
node.Data=' ';

Node n1=subsplit(0,s,splitingat);
Node n2= subsplit(1,splitingat+1,e);
node.Left=&n1; // danger Will Robinson!
node.Right=&n2;

return node;

You're taking the addresses of local, temporary, automatic variables and storing them in pointers that you return through node. As soon as that return executes, n1 and n2 are destroyed and node.Left and node.Right are left pointing to garbage. You may be able to fix this like so:

Node* n1=new Node(subsplit(0,s,splitingat)); 
Node* n2=new Node(subsplit(1,splitingat+1,e));
// side note: probably better to have subsplit() return dynamically-allocated Node*s to avoid the copy
node.Left=n1;
node.Right=n2;

but you may still have issues crop up if similar things are being done elsewhere.

Kind of along the same lines, in your second block of code, you are making a copy of each node you examine and storing it into sub. It would probably make more sense to have sub be a Node*.

And finally, to avoid memory management issues (almost) altogether, use shared_ptr<Node> instead of Node* in all of the above. :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top