【发布时间】:2013-03-27 03:03:58
【问题描述】:
好的。我正在使用一个简单的链表代码。
我将头节点保持为公开状态。然后我声明一个指针(head2)来存储主程序中第一个列表(first)的头节点。我声明了第二个名为 second 的列表,并将 head2 指定为第二个列表的头节点。然后我删除head2。然后我访问“第二个”的成员(其头节点被删除)并打印它们。我预计会出现分段错误。 但它有效,只为头节点的数据打印 0。令我不解的是,如果头节点被删除,那么头节点的next指针怎么还在内存中? (这是通过打印访问以遍历列表。我在 Ubuntu 中使用 g++ 4.6.1。这里是代码:
#include<iostream>
struct Node
{
int data;
Node* next;
};
class list1
{
public:
list1();
Node* head;
void insert(int);
void print();
};
list1::list1()
{
head=NULL;
}
void list1::insert(int a)
{
Node* newnode=new Node;
newnode->data=a;
newnode->next=head;
head=newnode;
}
void list1::print()
{
Node* dummy=head;
while(dummy)
{
std::cout<<dummy->data<<std::endl;
dummy=dummy->next;
}
}
int main()
{
list1 first;
first.insert(1);
first.insert(2);
first.insert(4);
first.insert(9);
list1 second;
Node* head2=new Node;
head2=first.head;
second.head=head2;
delete head2;
second.print();
return 0;
}
【问题讨论】:
-
你最好去google "C++ undefined behavior"
标签: c++ data-structures singly-linked-list