c - 线程 1:EXC_BAD_ACCESS(代码=1,地址=0x800000012)
问题描述
我试图通过各种其他线程查找此问题的解决方案,但我的搜索不成功。我是 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);
}
解决方案
当你分配 n 时,你永远不会设置 n->next。当您将它传递给 insert() 时,您会尝试访问错误的指针并崩溃。当您设置 n->ID 时,您应该将 n->next 设置为 NULL。
推荐阅读
- c# - ResourceLoader.GetString 带冒号
- c++ - 如何修复 LNK2019:vs 中未解析的外部符号
- docker - 尝试安装 Metron Docker 0.7.1 版本失败
- swift - 使用匹配的正则表达式代码替换单词
- javascript - 在 node.js 中异步读取多个文件
- scala - 使用scala spark从hdfs读取写入kafka,但得到NullPointerException
- html - 内容起伏太大以至于超出边际
- c++ - 当我尝试打印出我的数组时,我得到“0x7ffeedcf3a60”作为我的输出
- git - Pip 无法再从 https 克隆 - 错误 128
- python-3.x - 如何将类实例中的所有属性和函数复制到python中的另一个类?