Unexpected pointer behavior in C ++

I have a problem with my C ++ pointers, and it would be great if someone could share their experiences with me!

The output I get is:

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

Expected Result:

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

The relevance code is as follows:

my test.cpp

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

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; } 

Constructor for btree_node (which is mostly 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_; 

This is what I am changing. Initially, rbegin_ is set to an empty node constructor in the btree constructor with:

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

It looks like my node constructor, which does nothing, modifies the value of rbegin-> value () ....

Any help was appreciated.

+6
source share
1 answer

You got luck:

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

The error 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 memory "node" dynamically (malloc or so).
B. I don’t know what you are trying to do, but you insert each insert to replace the tree with the head with a new value and ignore the old head (for free?) ... I don’t think I want you to want to do it.

+6
source

Source: https://habr.com/ru/post/899395/


All Articles