c - 线程 1 : EXC_BAD_ACCESS (code=1, 地址=0x800000012)

标签 c

我试图通过各种其他线程查找此问题的解决方案,但我的搜索没有成功。我是 C 语言的新手,也是这个网站的新手,所以如果我对这个问题的措辞不正确,我会提前道歉。我有点知道发生了什么,但与此同时我可能完全错了。我有一个链接列表,我试图在列表的末尾插入。但是当 Xcode 到达语句 while(ptr->next!=NULL) 时它会抛出错误:

线程 1:EXC_BAD_ACCESS(代码=1,地址=0x800000012)

我之前在某处读到,这是因为我正在访问不存在的东西,或者我没有初始化 node->next 到 NULL 但我在前面的“if 语句”中做了。我在使用指针和链表进行编码方面还很陌生,我再次为我的代码中可能出现的任何奇怪的东西道歉):

////列表和节点结构

//data nodes
typedef struct node{
    int data;
    int ID;
    struct node* prev;
    struct node* next;
} node;


typedef struct ListInfo{
    int count; //numnodes
    struct node *list; //list of nodes
} ListInfo;

////插入函数

 void insert(ListInfo *H, node *n){
        if(n == NULL)
            return;

        node* ptr = H->list;
        if(H==NULL){
            ptr = n;
            ptr->next = NULL;
        }
        else{
            while(ptr->next!=NULL){ //Thread 1: EXC_BAD_ACCESS (code=1, address=0x800000012)
                ptr = ptr->next;
            }
            ptr = n;
            ptr->next = NULL;
        }
        // End of function
        return;
    } 

////主要内容

int main(){ // No Edititng is needed for the main function.

    ListInfo H;
    H.count =0;

    node *n;
    int Data = 0,ID =0 ;

    do{
        printf("Enter an ID and a Value to add to the list, Enter -1 to stop: ");
        //Get value from user to store in the new linked list node later.
        scanf("%d %d",&ID,&Data);

        // Check if the user entered "-1", if so exit the loop.
        if(Data == -1||ID == -1)
            return 0;

        // Allocate memory for a new Node to be added to the Linked List.
        n = malloc(sizeof(node));

        // Put the Data from the user into the linked list node.
        n->data = Data;
        n->ID = ID;

        //Increment the number of nodes in the list Header.
        // If the current node count is zero, this means that this node is the first node
        //   in this list.
        if(H.count++ == 0)
            H.list = n;
        // Otherwise, just use the insert function to add node to the list.
        else insert(&H,n);

    }while(Data != -1);

    // Display all nodes in the list.
    DisplayList(&H);


    //Remove a node from the list, and display the list each time.
    while(H.count != 0){
        Delete(&H,H.list->data);
        DisplayList(&H);
    }

    // Display the list, this should be empty if everything was correct.
    DisplayList(&H);
}

最佳答案

当你分配 n 时,你永远不会设置 n->next。当您将它传递给 insert() 时,您尝试访问坏指针并崩溃。当您设置 n->ID 时,您应该将 n->next 设置为 NULL。

关于c - 线程 1 : EXC_BAD_ACCESS (code=1, 地址=0x800000012),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58211064/

相关文章:

c - 使用strtok在c中分割一个字符串

c - 通过管道函数在 C 中计算行列式矩阵。修订代码

c - 指针数组上的合并排序实现

c++ - 尝试以相反的顺序使用 extern

c - 程序执行的时间计算?

c - 使用 libcurl 通过 HTTP POST 发送多个文件

c - 何时对数组使用指针与使用访问运算符的通用规则是什么?

c - GCC 内联汇编 : constraint for direct memory reference

根据出生日期计算年龄

C++ 表达式模板