Weird Behavior of std::cout

Cody

New Member
#1
I have a class for representing nodes in C++ but when printing the output out to with std::cout I am seeing a weird issue. Here is the class:
Mã:
class NodeInt
{
    public:
        int value;
        NodeInt* left;
        NodeInt* right;

        NodeInt()
        {
            left    = NULL;
            right   = NULL;
        };

        NodeInt(int val)
        {
            value = val;
            left    = NULL;
            right   = NULL;
        };

        void setValue(int val)
        {
            value = val;
        };

        void insertNode(int val)
        {
            if(val <= value )
            {
                if(left == NULL)
                {
                    NodeInt newNode;
                    newNode.setValue(val);
                    left = &newNode;
                }
                else
                {
                    left->insertNode(val);
                }
            }
            else
            {
                if(right == NULL)
                {
                    NodeInt newNode;
                    newNode.setValue(val);
                    right = &newNode;
                }
                else
                {
                    right->insertNode(val);
                }
            }
        };
};
Here is the main:
Mã:
int main()
{
    NodeInt firstN;
    firstN.setValue(27);
    firstN.insertNode(11);
    firstN.insertNode(29);
    firstN.insertNode(10);

    /**std::cout << firstN.value << std::endl;
    std::cout << firstN.left->value << std::endl;
    std::cout << firstN.right->value << std::endl;
    **/

    NodeInt* n = firstN.left;
    n = (n->left);
    std::cout << n->value << std::endl;

    return 0;
}
Now you'll see I have three std::cout lines commented out. As it is if I run the program right now it will output the correct value of 10. However, if I un-comment the lines it will change the 10 to 2130567168. Picture is showing what I mean:

IJlu8.png

What gives?
 

Admin

Administrator
Thành viên BQT
#2
You set the two pointers of your Node to point to function-local variables in insertNode() that will be gone when execution reaches the end of the block they are defined in. The output you get is pure luck.

If you want to do manual memory management you'll have to use new and delete and your class needs a copy-constructor, a copy-assignment-operator and a destructor. Please read The Rule of the Big Three (and a half) and The Rule of the Big Four (and a half) (aka The Rule of 3/5).

If you want to have an easier life however you can look up smart-pointers and how to use them and follow The Rule of Zero.
 
Top