Sooc
Sooc

Reputation: 141

How do you fix a segmentation fault

When I run my code I keep getting a message that I have a segmentation fault. I did a core dump with the GDB and it told me that my problem is with p = p->next; int the function below. Can someone help me understand what I did wrong and how I can go about fixing it? I know that segmentation faults have something to do with incorrect use of pointers but I am not sure what is wrong with p = p->next.

int list_size(const list_t *h) {
node_t *p = *h;
int r = 0;
do {
    r += 1;
    p = p->next;
} while (p);
return r;
}

Upvotes: 0

Views: 81

Answers (1)

R Sahu
R Sahu

Reputation: 206737

Check for null pointers before you use them.

Change

do {
    r += 1;
    p = p->next;
} while (p);

to

while (p)
{
    r += 1;
    p = p->next;
}

Upvotes: 3

Related Questions