C++ Pointer node

When I write my code in this way about the next one, it will return strange error.

struct Student{
    int val;
    Student* next;
    Student(int a){
        val = a;
        next = NULL;
    }
};
int main(){
Student begin(0);
Student *head = &begin;
Student *pointer = head;
for(int i=0;i<3;i++){
    pointer->val = i;
    Student next(0);
    pointer->next = &next;
    pointer = pointer->next;
}

while(head != NULL){
    cout<< head-> val<<endl;
    head = head ->next;
}
}

After I change the loop into this way, it works.

for(int i=0;i<3;i++){
    pointer->val = i;
    pointer->next = new Student(0);
    pointer = pointer->next;
}

Why this happen? Any differences between these two ways to initialize the next node?


You are setting up the node to point to a local stack variable, which is getting destroyed as you go to the next iteration of the for loop.

Your usage of new Student fixed this by making a heap allocation

Lots of good discussion on Heap vs Stack memory at Stack Memory vs Heap Memory


When you declare a student like this

Student next(0);

It allocates temporary memory on the stack that should only be considered usable within that block.

When you use new you allocate memory on the heap that can be used anywhere. Watch out for memory leaks and always define destructors.

new Student(0);

for(int i=0;i<3;i++){
   pointer->val = i;
   Student next(0);
   pointer->next = &next;
   pointer = pointer->next;
}

You are creating object student on automatic storage (commonly implemented as a stack). Then you are storing a pointer to this object in your linked list. When 'Student' goes out of scope the object is deleted. Now your pointer is a dangling pointer. De-referencing that pointer is now undefined behavior.

pointer->next = new Student(0);

Is created on dynamic storage (commonly implemented as a heap). This object will live until you tell it to die (delete it).

I suggest you read about the differences between the stack/heap in C++. It is a very important topic if you want to learn C++.

Also, make sure you deleted anything newed objects! If you don't you will end up with memory leaks in your programs.

链接地址: http://www.djcxy.com/p/79796.html

上一篇: 在方法内创建的对象

下一篇: C ++指针节点