【问题标题】:Thread 1: EXC_BAD_ACCESS (code=1, address=0x800000012)线程 1:EXC_BAD_ACCESS(代码=1,地址=0x800000012)
【发布时间】:2020-02-01 07:07:14
【问题描述】:

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

Thread 1: EXC_BAD_ACCESS (code=1, address=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);
}

【问题讨论】:

  • 你能把你的 main() 添加到问题中吗?

标签: c


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2018-03-13
    • 2013-10-11
    • 2019-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多