-3

Okay. I am paying around with a simple linked list code.

I keep the head node as public. then I declare a pointer (head2)to store the head node of the first list(first) in the main program. I declare a second list called second, and assign head2 as the head node of the second list. Then I delete head2. I then access the members of "second" (whose head node is deleted) and print them. I expected a segmentation fault. But it works, only printing 0 for the data of the head node. What is puzzling to me is that if the head node is deleted, how is the next pointer of the head node still in memory? (this is accessed by print to traverse through the list.I am using g++ 4.6.1 in Ubuntu.Here is the code:

#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;
}
4

2 回答 2

2

您的代码通过访问生命周期结束的对象来调用未定义的行为。

它可能仍然有效,这并不奇怪。

未定义的行为意味着任何事情都可能发生,包括你正在观察的事情。

于 2013-03-27T03:08:55.240 回答
1

删除内存只是将内存返回给系统,返回的内存准备好再次分配。但是内存中的数据仍然存在,直到内存被覆盖。由于您的程序已经删除了内存,并且您的程序不知道何时以及谁将再次分配内存块。因此,对于您的程序,仍然使用内存会导致未定义的行为。

于 2013-03-27T03:12:52.960 回答