编码SLL时获取中止陷阱6 我是C++新手。试图制作一个简单的单链表程序。代码如下。在这里,我创建了一个节点类、SLL类和相应的函数 #include <iostream> using namespace std; class Node{ private: int data; Node* next; friend class SLL; }; class SLL{ public: SLL(); ~SLL(); bool empty() const; const int& front() const; void addFront(const int& e); void removeFront(); void printList(); private: Node* head; }; SLL::SLL() :head(NULL){ } SLL::~SLL(){ while(!empty()) removeFront(); } bool SLL::empty() const{ return head == NULL; } void SLL::removeFront(){ Node* temp = head; head = temp->next; delete temp; } void SLL::addFront(const int& e){ Node* n = new Node; n->data = e; n->next = head; head = n; } void SLL::printList(){ Node* temp = head; // int n =0 ; while(temp->next){ // n++; cout<< temp->data << " "; temp = temp->next; } delete temp; } int main(){ SLL a; a.addFront(1); a.printList(); }

编码SLL时获取中止陷阱6 我是C++新手。试图制作一个简单的单链表程序。代码如下。在这里,我创建了一个节点类、SLL类和相应的函数 #include <iostream> using namespace std; class Node{ private: int data; Node* next; friend class SLL; }; class SLL{ public: SLL(); ~SLL(); bool empty() const; const int& front() const; void addFront(const int& e); void removeFront(); void printList(); private: Node* head; }; SLL::SLL() :head(NULL){ } SLL::~SLL(){ while(!empty()) removeFront(); } bool SLL::empty() const{ return head == NULL; } void SLL::removeFront(){ Node* temp = head; head = temp->next; delete temp; } void SLL::addFront(const int& e){ Node* n = new Node; n->data = e; n->next = head; head = n; } void SLL::printList(){ Node* temp = head; // int n =0 ; while(temp->next){ // n++; cout<< temp->data << " "; temp = temp->next; } delete temp; } int main(){ SLL a; a.addFront(1); a.printList(); },c++,linked-list,singly-linked-list,C++,Linked List,Singly Linked List,为什么会出现这种错误?解决这个问题的方法是什么?删除温度不会破坏变量temp;局部变量已经自动销毁。(事实上,技术术语是“自动存储持续时间”。)毕竟,在 void f(){ inti=std::rand(); std::它真的能告诉你如何调试它吗…@UnholySheep,temp只是浪费,所以在打印列表后删除它temp并不是用new关键字分配的,所以删除它会得到SIGABRT。那么,我们什么时候真的需要使用delete?@bigbountity:当你使用new时。你的书没有解释这一点吗?也许是

为什么会出现这种错误?解决这个问题的方法是什么?

删除温度printList中的code>不会破坏变量
temp
;局部变量已经自动销毁。(事实上,技术术语是“自动存储持续时间”。)毕竟,在

void f(){
inti=std::rand();

std::它真的能告诉你如何调试它吗…@UnholySheep,temp只是浪费,所以在打印列表后删除它
temp
并不是用new关键字分配的,所以删除它会得到
SIGABRT
。那么,我们什么时候真的需要使用delete?@bigbountity:当你使用
new
时。你的书没有解释这一点吗?也许是时候写一本更好的书了!“那么,我们什么时候真的需要使用delete?”-非常罕见,因为您通常应该使用智能指针和容器,而不是使用裸
new
delete
进行手动内存管理。
ol(36664,0x7fff8a6e0340) malloc: *** error for object 0x7fb055402820: pointer being freedwas not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6
void f() {
  int i=std::rand();
  std::cout << i;
}