Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Going through this question, one answer said the object created are destroyed outside their scope, To get this concept clearly I wrote the following code:

#include <iostream>

using namespace std;

struct Node{
    int val;
    Node *next;
    Node(int x) : val(x) , next(NULL){}
};

int main(){
    for(int i=0;i<10;i++){
        int someval = rand()%100;
        Node somenode = Node(someval);
        printf("Address for object %d is %p 
",i+1, &somenode);
    }
}

I got the following output:

Address for object 1 is 0x7ffc32ff26b0 
Address for object 2 is 0x7ffc32ff26b0 
Address for object 3 is 0x7ffc32ff26b0 
Address for object 4 is 0x7ffc32ff26b0 
Address for object 5 is 0x7ffc32ff26b0 
Address for object 6 is 0x7ffc32ff26b0 
Address for object 7 is 0x7ffc32ff26b0 
Address for object 8 is 0x7ffc32ff26b0 
Address for object 9 is 0x7ffc32ff26b0 
Address for object 10 is 0x7ffc32ff26b0 

I understand that each object is destroyed every time the loop iterates and a new object is created; but why do all of them have the same address. This problem occurred to me when I was creating a linked list and I did not use the new operator to create the object instead just used the same code, and the list always pointed to the same node and I ran into an infinite loop. Why is the same address allocated to each object?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
489 views
Welcome To Ask or Share your Answers For Others

1 Answer

You keep creating the object on the top of the stack, and then removing it (the object goes out of scope at the end of each loop iteration, and is deconstructed before the next iteration). Thus, the address of the top of the stack is the same everytime you allocate space for the object.

If you remove the loop and allocate multiple Nodes in a row, you'll see different addresses for each as the stack grows.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...