Aaron Wojnowski
Aaron Wojnowski

Reputation: 6480

C EXC_BAD_ACCESS Crash in Linked List

I am building a linked list in C which stores strings and allows you to search the linked list to see if an element exists. For some reason, every 2-3 times that I run the following code with a linked list containing around 6,000 elements, I get an EXC_BAD_ACCESS error on the following line:

if (strcmp(list->value, value) == 0) return true;

This EXC_BAD_ACCESS error is due to it accessing list->value. I don't understand why this could be since I never have a string larger than my LINE_BUFFER and I allocate my memory on to the heap before setting the value pointer. That means that that memory should never be deallocated, correct?

My line buffer declaration:

#define LINE_BUFFER 81

Here's the linked list Node struct:

struct Node {
    struct Node *next;
    char *value;
};
typedef struct Node Node;

Here's the linked list code:

Node * create_node(Node *list, char *value) {

    Node *node = malloc(sizeof(Node));
    node->value = strcpy(malloc(sizeof(char) * LINE_BUFFER), value); // make sure value is on the heap

    // find the end of the list
    Node *end = NULL;
    while (list) {

        end = list;
        list = list->next;

    }

    // add this node to the end if necessary
    if (end) {

        end->next = node;

    }

    return node;

}

Node * init_list(char *value) {

    Node *node = create_node(NULL, value);
    return node;

}

Node * add_list(Node *list, char *value) {

    Node *node = create_node(list, value);
    return node;

}

bool search_list(Node *list, char *value) {

    while (list) {

        if (strcmp(list->value, value) == 0) return true;
        list = list->next;

    }
    return false;

}

void free_list(Node *list) {

    if (!list) return;

    Node *next = list->next;
    free(list->value);
    free(list);
    free_list(next);

}

Upvotes: 0

Views: 217

Answers (1)

AShelly
AShelly

Reputation: 35580

It appears that you never initialize node->next to NULL in create_node. So walking the list will dereference uninitialized memory, and eventually crash when it contains invalid pointers.

Upvotes: 3

Related Questions