0

So I was working on the Max Heap Tree with link representation on C++. Since I cannot upload the code as it is pretty long but while I was debugging I realized that the execution will stop at the expression where it assgins Null pointer to a pointer. for example

// if node->left_child->right_chile == NULL
node->right_child = node->left_child->right_child; // the program will exit here.

This kind of operation often occurs in my code at the deletion method so I was also wondering if I assign NULL variable multiple times, it causes error. for example in continuition of above example,

node->parent->left_child = node->right_child;

I was trying to figure out how NULL pointer behaves but I cannot quite get it. Could you please help me?

  • 1
    "I cannot upload the code as it is pretty long" thats why you should post a [mcve]. Posting your complete code is rarely the right thing to do. Please follow the link and read about it – 463035818_is_not_an_ai May 06 '21 at 17:32
  • 1
    Most probably, `node->left_child == NULL` that is why it can not further access it's right child and simply throws an error. – Talal02 May 06 '21 at 17:34
  • Compile with -fsanitize=address, so you can see more detail of the error. It's probably due to you dereferencing a NULL pointer. – Hiram May 06 '21 at 17:34
  • Tip: In C++ you should be using `nullptr` instead of C's typeless `NULL`. – tadman May 06 '21 at 17:35
  • There is no guarantee by the C++ standard that the program will exit at that point. It's probably running into **undefined behavior** dereferencing a `nullptr`, and then the operating system has memory address `0x0000` trip a segv (violation trying to access an inaccessible segment). – Eljay May 06 '21 at 17:56

1 Answers1

2

Can you assign a NULL pointer variable to a pointer variable?

Yes. You can assign a pointer to another as long as the value of the that is assigned from has been initialised. If that value is null, it is OK. For example, this is fine:

Node* a = nullptr;
Node* b = nullptr;
a = b;
node->right_child = node->left_child->right_child; // the program will exit here.

This implies that one of node or node->left_child is probably not a valid pointer. Either of those would result in undefined behaviour.


P.S. Don't use the NULL macro in C++. It has bee obsoleted by nullptr.

eerorika
  • 232,697
  • 12
  • 197
  • 326