I am trying to create an AVL Tree and insert a node into it. Whenever I try to add a data value ın the tree node, my program crashes and returns the value 0xC0000005. This is how I have introduced the data item in the header file:
class AVLTreeNode
{
public:
int data;
AVLTreeNode();
virtual ~AVLTreeNode();
AVLTreeNode(int d, AVLTreeNode *leftChild, AVLTreeNode *rightChild);
AVLTreeNode *leftc;
AVLTreeNode *rightc;
int height;
}
Whenever I try to run the following lines of the code in the insert function, I get the crash.
AVLTreeNode *nw = NULL ;
nw->data = v;
I don't know what I'm doing wrong, please help me.
The return code of 0xC0000005 means STATUS_ACCESS_VIOLATION. (You can find this and other NT status codes on MSDN: NTSTATUS Values.) The error happens because NULL is outside the range of valid addresses for your program. Before dereferencing a pointer variable, you must assign it the address of a valid object. For example:
AVLTreeNode* nw = new AVLTreeNode{};
nw->data = v;
AVLTreeNode *nw = NULL;
This line of code sets nw to be a null pointer, in other words, it doesn’t point at anything. Trying to dereference a null pointer will result in undefined behaviour. You need to allocate memory for an AVLTreeNode object, and then get nw to point at it.
What you need instead is this, which allocates memory and points nw at it:
AVLTreeNode *nw = new AVLTreeNode;
And remember, whenever you allocate memory with new you need to deallocate it when you're finished with it:
delete nw;
User contributions licensed under CC BY-SA 3.0