Search code examples
c++pointersb-tree

Unexpected Pointer Behaviour in C++


I'm having a problem with my pointers in C++, and it would be great if someone was able to share their expertise with me!

The output I'm getting is:

1:
2:
END: C
1:C
2:E
END: E

The output I was expecting is:

1:
2:
END: C
1:C
2:C
END: E

The code of relevance is this:

my test.cpp

tree.insert('C');
tree.insert('E');

The insert function:

template <typename T> pair<typename btree<T>::iterator, bool> btree<T>::insert(const T& elem) {
  cout <<  "1:" << this->rbegin_->value() << endl;
  btree_node<T> node(elem);
  cout <<  "2:" << this->rbegin_->value() << endl;
  rbegin_ = &node;
  iterator itr;
  pair<typename btree<T>::iterator, bool> p(itr, false);
  cout << "END: " << this->rbegin_->value() << endl;
  return p;
}

The constructor for btree_node (which is basically empty):

template <typename T> btree_node<T>::btree_node(const T& elem) : value_(elem), nextCont_(NULL), prevCont_(NULL), nextNode_(NULL), prevNode_(NULL) {}

The btree class has a private variable:

btree_node<T>* rbegin_;

Which is what I'm modifying. rbegin_ is initially set to an empty node in the btree constructor with:

btree_node<T> end(NULL);
rbegin_ = &end;

It seems like my node constructor, which does nothing, is modifying the value of rbegin->value()....

Any help appreciated.


Solution

  • You got it by luck:

    1:
    2:
    END: C
    1:C     <--- Undefined.
    2:E
    END: E
    

    The mistake is here:

    template <typename T> pair<typename btree<T>::iterator, bool> btree<T>::insert(const T& elem) {
      cout <<  "1:" << this->rbegin_->value() << endl;
      btree_node<T> node(elem); /* LOCAL parameter, will be deleted when leaving scope*/
      cout <<  "2:" << this->rbegin_->value() << endl;
      rbegin_ = &node; /* Pointing to a LOCAL parameter, when leaving the scope it will point to undefined memory. */
      iterator itr;
      pair<typename btree<T>::iterator, bool> p(itr, false);
      cout << "END: " << this->rbegin_->value() << endl;
      return p;
    }
    

    So:
    A. Allocate the memory of "node" dynamically (malloc or so).
    B. I don't know what you are trying to do, but you make every insert to replace the tree head with the new value and ignoring the old head (free?)... I don't think that's want you wish to do.