bsmith bsmith - 2 months ago 5
C Question

C segfault when looping over a list

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.

Answer

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.

Comments