-4

I have this code:

while (current->next->data <= temp->data && current->next != nullptr)
        {
            current = current->next;
        }

when I run it i get the error:

Exception thrown: read access violation. current->next was nullptr.

I believe I should not be receiving this error because it is the exact thing I check for; I am new to this, is there something I am doing wrong?

3 Answers3

1
while (current->next->data <= temp->data && current->next != nullptr)

This will fail for the very first iteration if current->next is null. You should swap the order of condition check.

while (current->next != nullptr && current->next->data <= temp->data)
Gaurav Sehgal
  • 7,422
  • 2
  • 18
  • 34
0

By the http://en.cppreference.com/w/cpp/language/operator_logical

lhs && rhs

For the built-in logical AND operator, the result is true if both operands are true. Otherwise, the result is false. This operator is short-circuiting: if the first operand is false, the second operand is not evaluated

The lhs expression will be executed first, so you should put your current->next null pointer check at the left side of && in condition.

Community
  • 1
  • 1
Chen OT
  • 3,486
  • 2
  • 24
  • 46
0

Standard says [expr.log.and]

The && operator groups left-to-right. The operands are both contextually converted to bool (Clause 7). The result is true if both operands are true and false otherwise. Unlike &, && guarantees left-to-right evaluation: the second operand is not evaluated if the first operand is false.

So, in

current->next->data <= temp->data && current->next != nullptr

First evaluated first operand which is current->next->data <= temp->data. And here you have the error if current->next is nullptr.

Yola
  • 18,496
  • 11
  • 65
  • 106