Ross Satchell Ross Satchell - 3 months ago 10
C Question

Segmentation Fault when counting elements in linked list

I am new to linked lists, but am trying to create a linked list with 3 elements and to write a function that counts the number of elements in said linked list.
I keep getting a segmentation fault, but I can't figure out why.
Any help would be most welcome.

#include <stdio.h>
#include <stdlib.h>

typedef struct node { // create a struct to build a
int data; // linked list
struct node* next;
};

struct node* BuildOneTwoThree() {
struct node* head = NULL; // pointers
struct node* second = NULL; // for
struct node* third = NULL; // linked list

// allocate memory on the heap for the 3 nodes
head = malloc(sizeof(struct node));
second = malloc(sizeof(struct node));
third = malloc(sizeof(struct node));

head->data = 1; // set up 1st node
head->next = second;

second->data = 2; // set up 2nd node
second->next = third;

third->data = 3; // set up 3rd node
third->next = NULL;

return head;

}

void main(){
int num = Length(BuildOneTwoThree);
printf("Number of nodes:%d\n", num);


}

int Length(struct node* head) {
struct node* current = head;
int count = 0;

while(current != NULL) {
count++;
current = current->next;
}
return count;
}

Answer

The line

int num = Length(BuildOneTwoThree);

needs to be

int num = Length(BuildOneTwoThree());
                                 ^^^ Missing the function call.

Without that, you are justing the function pointer to Length.

You can avoid such errors by providing declarations of functions before using them.

struct node* BuildOneTwoThree();
int Length(struct node* head);

With the functions declared at the top of the file, I get the following message from gcc:

soc.c: In function ‘main’:
soc.c:36:22: warning: passing argument 1 of ‘Length’ from incompatible pointer type [-Wincompatible-pointer-types]
     int num = Length(BuildOneTwoThree);
                      ^
soc.c:10:5: note: expected ‘struct node *’ but argument is of type ‘struct node * (*)()’
 int Length(struct node* head);

typedef struct node {
    int             data;
    struct node*    next;
};

is not right. That produces the useless storage class specifier in empty declaration warning. That needs to be either

struct node {
    int             data;
    struct node*    next;
};

or

struct node {
    int             data;
    struct node*    next;
} node;

Also, the return type of main needs to be int, not void.

Comments