Tom Brunoli
Tom Brunoli

Reputation: 3466

Address boundary error on my linked list count function in C

I'm implementing a linked list library to teach myself C. I've got most things working nicely except iteration, which is being used for the length function I've made. Here's the structs used for the list

typedef struct ListNode ListNode;
typedef struct List List;

struct ListNode {
    void *val;
    ListNode *next;
};

struct List {
    ListNode *head;
};

I've also got a couple of other functions for manipulating the list, namely a create, push and pop function. Here's the create function if it matters:

List *list_create(){
    List *list = malloc(sizeof *list);
    return list;
}

Here's the function that's having issues, though:

int list_length(List *list){
    ListNode *current = list->head;
    int count = 0;

    // Iterate through the list, adding to the count
    while(current != NULL){
        count++;
        current = current->next;
    }

    return count;
}

For some reason when it reaches the last iteration, the while predicate doesn't work and instead, I get the following error:

Job 1, './linked_list ' terminated by signal SIGSEGV (Address boundary error)

Is there anything immediately obvious that I'm doing wrong? You can find all the (not completely working) code at https://github.com/tominated/linked_list

Upvotes: 2

Views: 682

Answers (1)

simonc
simonc

Reputation: 42175

list_create leaves head uninitialised. list_push (in your github code) creates a new item and sets head to its next pointer. When you iterate through the list, the last item points to this uninitialised pointer rather than to NULL. From this point on, you are into undefined behaviour; the chances are high you'll quickly get a SIGSEGV.

The fix is simple - you just need to set head to NULL when you create the list.

List *list_create(){
    List *list = malloc(sizeof *list);
    if (list != NULL) {
        list->head = NULL;
    }
    return list;
}

Upvotes: 5

Related Questions