D
D
Davidaa_WoW2021-10-14 16:09:11
C++ / C#
Davidaa_WoW, 2021-10-14 16:09:11

Why is an infinite pointer created in the tree?

I'm trying to read from a binary file into a search tree. But at one point, where there should be a null pointer, for some reason, an infinite pointer to itself appears. For a long time I searched for the cause with a debugger, but I did not find it. Maybe a side view would help?

struct Tree
{
    Tree* left = 0;
    Tree* right = 0;
    int key;
    int size = 1;
    string brand;
    string name;
};

Tree* insert(Tree* tree, int key, string brand, string name)
{
    if (!tree) {
        Tree* newtree = new Tree();
        newtree->key = key;
        newtree->brand = brand;
        newtree->name = name;
        return newtree;
    }
    if (tree->key > key)
        tree->left = insert(tree->left, key, brand, name);
    else
        tree->right = insert(tree->right, key, brand, name);
    return tree;
}

Tree * readElement(Tree* tree) {
    string brand;
    string name;
    int carNumber;
    int len;
    char* buf;
    int left, right;
    iffile.read((char*)&carNumber, 4);
    iffile.read((char*)&len, 4);
    buf = new char[len];
    iffile.read(buf, len);
    brand = buf;
    delete[]buf;
    iffile.read((char*)&len, 4);
    buf = new char[len];
    iffile.read(buf, len);
    name = buf;
    delete[]buf;
    tree = insert(tree, carNumber, brand, name);
    iffile.read((char*)&left, 4);
    if (left) {
        tree->left = readElement(tree);
    }
    else {
        tree->left = 0;
    }
    iffile.read((char*)&right, 4);
    if (right) {
        tree->right = readElement(tree);
    }
    else {
        tree->right = 0;
    }
    return tree;
}

Tree* readFromFile(Tree* tree) {
    iffile.open(filePath, ios::binary | ios::in);
    tree = readElement(tree);
    iffile.close();
    return tree;
}


There is no problem with the structure of the binary file itself, the elements are perfectly readable one by one, everything breaks only when links begin to be set.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2021-10-14
@Davidaa_WoW

This code creates a circular link:

if (left) {
        tree->left = readElement(tree);
    }

What are you trying to do there? If you want to read an element into a tree, then your readElement(tree) will return a pointer to the new root. If you want to add to the left subtree (and grant that the next element will be less than the root), then you need to add to tree->left and not tree.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question