简体   繁体   English

链接列表中的C EXC_BAD_ACCESS崩溃

[英]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. 我正在C中建立一个链表,该链表存储字符串,并允许您搜索链表以查看元素是否存在。 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: 出于某种原因,我每隔2-3次运行以下代码并使用包含约6,000个元素的EXC_BAD_ACCESS ,就会在以下行中收到EXC_BAD_ACCESS错误:

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

This EXC_BAD_ACCESS error is due to it accessing list->value. 这个EXC_BAD_ACCESS错误是由于它访问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. 我不明白为什么会这样,因为我从来没有一个大于LINE_BUFFER的字符串,并且在设置值指针之前我将内存分配给了堆。 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: 这是链接列表Node结构:

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);

}

It appears that you never initialize node->next to NULL in create_node . 看来您永远不会在create_node中将node->next初始化为NULL So walking the list will dereference uninitialized memory, and eventually crash when it contains invalid pointers. 因此,遍历该列表将取消引用未初始化的内存,并最终在包含无效指针时崩溃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM