Linked List length function

For a school project, I have to implement a forward-linked list, and the code I am using for the length() function works by traversing the entire list until the Next pointer is invalid. Unfortunately, it segfaults each time, just after tmp becomes invalid.

1
2
3
4
5
6
7
  size_t Node_Root::length() {
    Node *tmp = First; size_t count = 0;
    while (tmp) {
      if (tmp->Next) tmp = tmp->Next; else break;
    }
  return count;
  }


Node_Root is the manager for the list, and contains a member Node *First, while Node contains a member Node *Next. Both of these are set by default to null in the relevant constructors.
The only thing I can see is that you're not incrementing count inside your loop, so it'll always return 0.
Other than that, from just this piece of code, I'm not seeing any reason why it's segfaulting.
Oops, I removed that line after I mistook it for a comment. That's what I get for only skimming my code because I thought I knew what I had written. Otherwise, I'm not sure what else I should be including, have any suggestions?

Edit: It would seem that the issue is that Next somehow (and consistently) ends up being 0x1 when it reaches the end. Therefore, Next is invalid but not null. I don't know where this might occur, however, because the only assignments to Next anywhere are either Next = nullptr or Next = new Node
Last edited on
Well, in a turn of events that confuses me as much as anyone, outsourcing the check to an isLast() function, whose body is literally return (bool)Next seems to have cleared up the issue of Next equaling 0x1

My final function reads thus:

1
2
3
4
5
6
7
8
9
10
    size_t Node_Root::length() {
        Node *tmp = First;
        size_t count = 0;
        while (tmp) {
            count++;
            if (!(*tmp).isLast()) tmp = tmp->Next;
            else break;
        }
        return count;
    }
Last edited on
Topic archived. No new replies allowed.