我正在用 C 构建一个链表,它存储字符串并允许您搜索链表以查看某个元素是否存在。出于某种原因,我使用包含大约 6,000 个元素的链表运行以下代码每 2-3 次,就会在以下行中收到 EXC_BAD_ACCESS
错误:
if (strcmp(list->value, value) == 0) return true;
此 EXC_BAD_ACCESS
错误是由于它访问 list->value。我不明白为什么会这样,因为我从来没有一个字符串大于我的 LINE_BUFFER
并且我在设置值指针之前将内存分配到堆上。这意味着永远不应该释放该内存,对吗?
我的行缓冲区声明:
#define LINE_BUFFER 81
这是链表 Node
结构:
struct Node {
struct Node *next;
char *value;
};
typedef struct Node Node;
链表代码如下:
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);
}
最佳答案
您似乎从未在 create_node
中将 node->next
初始化为 NULL
。因此遍历列表将取消引用未初始化的内存,并最终在包含无效指针时崩溃。
关于C EXC_BAD_ACCESS 链表崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26384524/