为什么这个链接代码的C++代码插入会导致分段错误?
我在LinkedList中编写了两个函数,分别用于在Begging处插入和在末尾插入。但是,它显示了分段错误。为什么我的代码会出现分段错误为什么这个链接代码的C++代码插入会导致分段错误?,c++,linked-list,C++,Linked List,我在LinkedList中编写了两个函数,分别用于在Begging处插入和在末尾插入。但是,它显示了分段错误。为什么我的代码会出现分段错误 /*Structure of the linked list node is as struct Node { int data; struct Node * next; Node(int x) { data = x; next = NULL; } }; */ // function inserts the data in
/*Structure of the linked list node is as
struct Node {
int data;
struct Node * next;
Node(int x) {
data = x;
next = NULL;
}
}; */
// function inserts the data in front of the list
Node *insertAtBegining(Node *head, int newData) {
Node* newnode;
newnode->data = newData;
newnode->next = head;
head = newnode;
return head;
}
// function appends the data at the end of the list
Node *insertAtEnd(Node *head, int newData) {
Node* newnode;
newnode->data = newData;
newnode->next = NULL;
Node* temp;
temp = head;
while(temp->next!=NULL){
temp = temp->next;
}
temp->next = newnode;
return head;
}
newnode在这两个函数中都是局部变量,是堆栈分配的。因此,当范围完成时,它将消失 您必须从堆而不是堆栈分配新的内存区域 解决方案:
Node* newnode = (Node*)calloc(sizeof(Node),1);
在这里,您可以通过一个不确定的指针进行间接操作,就像它指向一个对象一样。程序的行为是不精确的。您无法真正知道指针指向何处,在将数据指向实际地址或为其分配内存之前,您不应尝试访问数据。将指针声明为null是一种很好的做法,以避免类似这样的错误。 例如: 当然,这一切都在网上。
别忘了释放内存什么线路分段故障?那将对我们很有帮助。另外,没有main方法,所以我们无法重现您的问题。newnode在两个函数中都是局部变量,堆栈分配。因此,当范围完成时,它将消失。
Node* newnode;
newnode->data = newData;
newnode->next = head;
Node* newnode = NULL;
newnode = (Node*)malloc(sizeof(Node));
ewnode->data = newData;
newnode->next = head;