1

Here is my list struct:

typedef struct Header {
  struct Header* next;
  char empty;
  int storageSize;
} Header;

And I am looping over a list to check how many elements its has:

int listSize(Header* _header) {
  int count = 0;
  while(_header->next) {
    _header = _header->next;
    ++count;
  }

  return count;
}

And I get a segfault after reaching the end of the list. However if I change it to:

int listSize(Header* _header) {
  int count = 0;
  while(_header->next) {
    if(!_header->next) {
      _header = _header->next;
      ++count;
    }
    else
      break;
  }

  return count;
}

It doesn't segfault, but it also obviously doesn't count the elements right.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
bsmith
  • 31
  • 3
  • 3
    Use a debugger. And if you really need help after exhausting all other debugging efforts then provide a [mcve]. – kaylum Sep 22 '16 at 01:03
  • I used lldb, but it doesn't segfault when use it. – bsmith Sep 22 '16 at 01:04
  • 1
    Could you add how you build your list? – vmonteco Sep 22 '16 at 01:05
  • 1
    I think `while(_header->next) {` should be `while(_header) {` – Ed Heal Sep 22 '16 at 01:05
  • You won't pass the case where you pass `NULL` to `listSize()`. – vmonteco Sep 22 '16 at 01:05
  • 1
    @BenSmith your edit makes all the comments/answers so far pretty much useless, and you are actually asking a new question, *without* providing a minimal example of your code. Please take a moment understanding what you have been told here, and if needed, post a new question, with an improved version of your code and a **minimal example**. Thank you. – gsamaras Sep 22 '16 at 01:31

3 Answers3

2

Change this:

while(_header->next) {

to this:

while(_header) {

since you want to loop over your list, as long as the current node is not NULL.

You were facing a segmentation fault, because you were trying to get the next data member of NULL.

It feels like you are passing an empty list to your listSize(), that is that the _header is NULL, and you are trying to get the next data member of NULL, thus a segmentation fault.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • Well, in [tag:C++] at least [it's not common](http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier), and you can see [tag:c] traits on that one... – gsamaras Sep 22 '16 at 01:08
0

You logic is incorrect. The code should be this - and note the comments

int listSize(Header* header) {
  int count = 0;
    while (header) {             // We have a node to count
      ++count;                   // Count it
      header = header->next;     // And move to the next node 
    }

   return count;
 }
Ed Heal
  • 59,252
  • 17
  • 87
  • 127
-1

In my opinion you can initialize next as 0 or *next as 0 whenever you want to create a new node.

Box Box Box Box
  • 5,094
  • 10
  • 49
  • 67
X Silence
  • 9
  • 1