-2

While going through runtime, I'm getting a nullptr exception while this code is executing.

bool Tree::Insert(int n)
{
    if (root == nullptr) // This is where it throws
    {
        Node* root = new Node(n);
        return true;
    }

Initialization in Tree.h

private:
Node* root;

and Tree constructor.

Tree::Tree()
{
    root = nullptr;
}

I have coded exactly like this before and it never threw an exception.

UPDATE: I apologize for the confusion on the extra '}' Tree::Insert(). There's more code in there and they all have a return case. I had this before

Node* newNode = new Node(n);
root = newNode;

but changed it for a different reason.

Node.h

#pragma once

struct Node
{
    int data;
    Node *left;
    Node *right;

    // Constructor
    Node() { data = 0; left = nullptr; right = nullptr; }
    // Parameterized
    Node(int d) { data = d; left = nullptr; right = nullptr; }
    // Destructor
    ~Node() { data = 0; }
};

2 Answers2

2

You either access the Tree::Insert member directly (i.e. not via an instance of the Tree class as if it was a static member) or the instance of the Tree class you're using to access the Insert method is not initialized.

In other words, this is null.

Dmitry Egorov
  • 9,542
  • 3
  • 22
  • 40
  • @TobySpeight, exactly! This is what I was typing when noticed your comment. – Dmitry Egorov Mar 17 '17 at 08:58
  • I'm such an idiot. The issue was in my driver. rather then properly initializing it by typing "Tree* Binary_Tree = new Tree;" I instead typed "Tree* Binary_Tree;" Because of this, the constructor wasn't called. – Daniel Espinel Mar 17 '17 at 09:01
-2

nullptr is implementation-specific. when you say, "I have coded exactly like this before and it never threw an exception." you may have to check if it was on a different compiler.

venki
  • 35
  • 6
  • `nullptr` is not implementation-specific an any meaningful sense here. `nullptr_t::operator==` is fully specified in the standard. – Toby Speight Mar 17 '17 at 09:37