#include "stdafx.h" #include <iostream> using namespace std; struct Node { int Key; Node* Left; Node* Right; }; class Tree { public: Node* Top; Tree() { Top = NULL; } Node* GetTop() { return Top; } void Build(Node* x) { Node* T2 = new Node(); x->Left = T2; x->Left->Key = 2; } }; int main() { Tree T; T.Build(T.GetTop()); cout << T.GetTop()->Left->Key; return 0; } 

Displays error on line

 x->Left = T2; 

An unhandled exception was raised: write access violation.

x was nullptr.

If there is a handler for this exception, program execution can continue safely.

How to fix?

  • 2
    Apparently you need to add a check that inside the Build function, the x parameter can be NULL and handle this case in a special way. - KoVadim

1 answer 1

Tree T; - a new instance of the Tree class is created, and the default constructor is called, in which Top is NULL .

T.Build(T.GetTop()); - first call the function GetTop() , which returns NULL and pass this value as an argument to the function Build() . Inside this function, the variable x is NULL , as we just found out. You use x->Left , so you get an error.