-6

I have simple question on C++ linked list. Say I am given a list, I just want to print for each node the value. I found this simple code on the net

while (head!= NULL) {
        cout << head->data;
        head= head->next;
    }

which works just fine.

If I do the following

cout << head->data; 
head= head->next;
cout << head->data << endl;

I get the following error (on LeetCode)

Line 20: Char 25: runtime error: member access within null pointer of type 'ListNode' (solution.cpp) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:29:25

I do not understand what I am missing.

9
  • Actually, you set head=head->next and then use head without checking whether its null or not. If null, using head->data will cause some trouble. Commented Jun 26 at 21:52
  • 1
    My personal choice is fmt::printlin("{}", fmt::join(listname, ", ")); You seem to not want a loop? What would your proposed solution look like if the list contains 3 elements? 200? And given that you're working on a LeetCode solution, are you restricted to the standard library, or is this for personal checks before cleaning up for submission? Commented Jun 26 at 21:53
  • @abcdefg I initially thought that's what was causing the issue but to b emore specific, I do test whether the head is not null and the result is true. So I do not think that is the reason Commented Jun 26 at 21:57
  • 1
    It's called dereferencing a null ponter. Your first code sample avoids that. Your second (crashing) code sample fails to avoid that. A null pointer is a pointer that you can't dereference Commented Jun 27 at 2:45
  • 2
    Seems someone is trying you to teach you "C"... For crying out loud this is 2025 and std::list has been a part of C++ for ages now. It exists to avoid all the pointer @$## you are running into now Commented Jun 27 at 4:52

2 Answers 2

4
cout << head->data;          //head could be NULL
head = head->next;           //head->next could be NULL, hence head would be NULL
cout << head->data << endl;  //head could be NULL

As you can see, all three lines can lead to undefined behavior (or a segfault), due to dereferencing a NULL pointer.

Whereas the previous snippet:

while (head != NULL) {
    cout << head->data;
    head = head->next;
}

is safe, because you always have a test if head == NULL, and therefore never reach the point where the members of head are accessed (head->data, head->next), needless to say that the entire block is skipped if the test fails (if head == NULL).

Sign up to request clarification or add additional context in comments.

3 Comments

So, the key takeaway is always validating pointer before dereference. And using the while(head) loop is the simplest and most idiomatic pattern for traversing and printing linked lists?
@Hawk whenever you dereference a pointer, the pointer MUST be non-null. So yes, it should be tested all the time. But in a synchronize function call, you may just test it in the beginnin.
@Hawk Yes, validating pointers (before dereferencing) is a must do. When a pointer is passed as argument to a function, one would first test (assert) for NULL. In case of list items, you'll probably find something like this: for (item_ptr item = head; item; item = item->next) {...}, but in modern C++, one would typically use iterators and test if some iterator has reached the end marker (e.g. pos != end), and there are still all algorithm functions, which essentially makes manual iteration obsolete.
1

You are not checking if head is NULL before accessing its data.

In the first code snippet there is a check that validates that head is not NULL before accessing its data.

2 Comments

The same comment was raised by someone else and I do not think this is the issue.
The error message said exactly that "member access within null pointer of type 'ListNode' (solution.cpp) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:29:25" Which was exactly that. Your code attempted to dereference a null pointer on line 29 of solution.cpp.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.