C++ scope on heap





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







1















Why I am getting output as 10 after deleting it's scope? I have created a class A which has a pointer type member variable and another class B which has another member variable x. Now I am allocating memory on heap for B with value 10 for x. To create instance of class A, I have used memory address of x. Now I am deleting object b and printing value of pointer ref of class A.
I am getting why I am getting output as 10 as we can see that memory holding that value is no longer persisting on heap?



#include<iostream>
using namespace std;

class A
{
public:
int *ref;
A(int *ref):ref(ref)
{
}
};

class B{
public:
int x;
B(int x):x(x){}
};

int main()
{
B *b=new B(10);
A a(&b->x);
delete b;
cout<<*a.ref<<endl;
}









share|improve this question























  • Nearly all of the delete operations in PC to not erase resources, but just free the space they occupied for future use. So the data might still exists for a certain amount of time, but the outcome of accessing that data is undefined.

    – t.niese
    Jan 4 at 7:53






  • 1





    Off topic but you are using the term scope in the wrong way. Scope refers to the part of the source code where a name is visible. It does not refer to the lifetime of a variable, that's usually called extent. So data allocated on the heap has indefinite extent (because it lives until you delete it) but any pointer variables pointing at that data have the normal scope rules.

    – john
    Jan 4 at 8:15




















1















Why I am getting output as 10 after deleting it's scope? I have created a class A which has a pointer type member variable and another class B which has another member variable x. Now I am allocating memory on heap for B with value 10 for x. To create instance of class A, I have used memory address of x. Now I am deleting object b and printing value of pointer ref of class A.
I am getting why I am getting output as 10 as we can see that memory holding that value is no longer persisting on heap?



#include<iostream>
using namespace std;

class A
{
public:
int *ref;
A(int *ref):ref(ref)
{
}
};

class B{
public:
int x;
B(int x):x(x){}
};

int main()
{
B *b=new B(10);
A a(&b->x);
delete b;
cout<<*a.ref<<endl;
}









share|improve this question























  • Nearly all of the delete operations in PC to not erase resources, but just free the space they occupied for future use. So the data might still exists for a certain amount of time, but the outcome of accessing that data is undefined.

    – t.niese
    Jan 4 at 7:53






  • 1





    Off topic but you are using the term scope in the wrong way. Scope refers to the part of the source code where a name is visible. It does not refer to the lifetime of a variable, that's usually called extent. So data allocated on the heap has indefinite extent (because it lives until you delete it) but any pointer variables pointing at that data have the normal scope rules.

    – john
    Jan 4 at 8:15
















1












1








1








Why I am getting output as 10 after deleting it's scope? I have created a class A which has a pointer type member variable and another class B which has another member variable x. Now I am allocating memory on heap for B with value 10 for x. To create instance of class A, I have used memory address of x. Now I am deleting object b and printing value of pointer ref of class A.
I am getting why I am getting output as 10 as we can see that memory holding that value is no longer persisting on heap?



#include<iostream>
using namespace std;

class A
{
public:
int *ref;
A(int *ref):ref(ref)
{
}
};

class B{
public:
int x;
B(int x):x(x){}
};

int main()
{
B *b=new B(10);
A a(&b->x);
delete b;
cout<<*a.ref<<endl;
}









share|improve this question














Why I am getting output as 10 after deleting it's scope? I have created a class A which has a pointer type member variable and another class B which has another member variable x. Now I am allocating memory on heap for B with value 10 for x. To create instance of class A, I have used memory address of x. Now I am deleting object b and printing value of pointer ref of class A.
I am getting why I am getting output as 10 as we can see that memory holding that value is no longer persisting on heap?



#include<iostream>
using namespace std;

class A
{
public:
int *ref;
A(int *ref):ref(ref)
{
}
};

class B{
public:
int x;
B(int x):x(x){}
};

int main()
{
B *b=new B(10);
A a(&b->x);
delete b;
cout<<*a.ref<<endl;
}






c++ scope heap heap-memory






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jan 4 at 7:45









Pankaj KumarPankaj Kumar

61




61













  • Nearly all of the delete operations in PC to not erase resources, but just free the space they occupied for future use. So the data might still exists for a certain amount of time, but the outcome of accessing that data is undefined.

    – t.niese
    Jan 4 at 7:53






  • 1





    Off topic but you are using the term scope in the wrong way. Scope refers to the part of the source code where a name is visible. It does not refer to the lifetime of a variable, that's usually called extent. So data allocated on the heap has indefinite extent (because it lives until you delete it) but any pointer variables pointing at that data have the normal scope rules.

    – john
    Jan 4 at 8:15





















  • Nearly all of the delete operations in PC to not erase resources, but just free the space they occupied for future use. So the data might still exists for a certain amount of time, but the outcome of accessing that data is undefined.

    – t.niese
    Jan 4 at 7:53






  • 1





    Off topic but you are using the term scope in the wrong way. Scope refers to the part of the source code where a name is visible. It does not refer to the lifetime of a variable, that's usually called extent. So data allocated on the heap has indefinite extent (because it lives until you delete it) but any pointer variables pointing at that data have the normal scope rules.

    – john
    Jan 4 at 8:15



















Nearly all of the delete operations in PC to not erase resources, but just free the space they occupied for future use. So the data might still exists for a certain amount of time, but the outcome of accessing that data is undefined.

– t.niese
Jan 4 at 7:53





Nearly all of the delete operations in PC to not erase resources, but just free the space they occupied for future use. So the data might still exists for a certain amount of time, but the outcome of accessing that data is undefined.

– t.niese
Jan 4 at 7:53




1




1





Off topic but you are using the term scope in the wrong way. Scope refers to the part of the source code where a name is visible. It does not refer to the lifetime of a variable, that's usually called extent. So data allocated on the heap has indefinite extent (because it lives until you delete it) but any pointer variables pointing at that data have the normal scope rules.

– john
Jan 4 at 8:15







Off topic but you are using the term scope in the wrong way. Scope refers to the part of the source code where a name is visible. It does not refer to the lifetime of a variable, that's usually called extent. So data allocated on the heap has indefinite extent (because it lives until you delete it) but any pointer variables pointing at that data have the normal scope rules.

– john
Jan 4 at 8:15














3 Answers
3






active

oldest

votes


















4














It's undefined behavior. Case in point, when I run your exmple in MSVC, my output is -572662307.



There's no guarantee on what happens if you try to access invalid memory. What will likely happen is that it accesses the invalid memory anyway, and if that memory hasn't changed, you may get the old value. That's actually a bad thing, because it appears that the program is working as intended, when in reality it isn't.




I am getting why I am getting output as 10 as we can see that memory
holding that value is no longer persisting on heap?




The memory is not valid anymore, but the number 10 may still be in that memory, and a.ref is still pointing to that memory. So even if the memory isn't valid, the 10 may still persist.






share|improve this answer

































    0














    What you have is undefined behavior because the program is accessing memory that does not belong to it anymore.
    delete frees the memory so that it can be reused, but that does not mean that value in that memory location is set to zero (if that is what you were expecting).






    share|improve this answer































      0














      It is because of Dangling pointer effect. Although we have deleted the memory data is not yet erased or not other data being stored over there and our pointer is still pointing to that memory.



      for reference
      https://www.geeksforgeeks.org/dangling-void-null-wild-pointers/






      share|improve this answer
























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54034897%2fc-scope-on-heap%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        4














        It's undefined behavior. Case in point, when I run your exmple in MSVC, my output is -572662307.



        There's no guarantee on what happens if you try to access invalid memory. What will likely happen is that it accesses the invalid memory anyway, and if that memory hasn't changed, you may get the old value. That's actually a bad thing, because it appears that the program is working as intended, when in reality it isn't.




        I am getting why I am getting output as 10 as we can see that memory
        holding that value is no longer persisting on heap?




        The memory is not valid anymore, but the number 10 may still be in that memory, and a.ref is still pointing to that memory. So even if the memory isn't valid, the 10 may still persist.






        share|improve this answer






























          4














          It's undefined behavior. Case in point, when I run your exmple in MSVC, my output is -572662307.



          There's no guarantee on what happens if you try to access invalid memory. What will likely happen is that it accesses the invalid memory anyway, and if that memory hasn't changed, you may get the old value. That's actually a bad thing, because it appears that the program is working as intended, when in reality it isn't.




          I am getting why I am getting output as 10 as we can see that memory
          holding that value is no longer persisting on heap?




          The memory is not valid anymore, but the number 10 may still be in that memory, and a.ref is still pointing to that memory. So even if the memory isn't valid, the 10 may still persist.






          share|improve this answer




























            4












            4








            4







            It's undefined behavior. Case in point, when I run your exmple in MSVC, my output is -572662307.



            There's no guarantee on what happens if you try to access invalid memory. What will likely happen is that it accesses the invalid memory anyway, and if that memory hasn't changed, you may get the old value. That's actually a bad thing, because it appears that the program is working as intended, when in reality it isn't.




            I am getting why I am getting output as 10 as we can see that memory
            holding that value is no longer persisting on heap?




            The memory is not valid anymore, but the number 10 may still be in that memory, and a.ref is still pointing to that memory. So even if the memory isn't valid, the 10 may still persist.






            share|improve this answer















            It's undefined behavior. Case in point, when I run your exmple in MSVC, my output is -572662307.



            There's no guarantee on what happens if you try to access invalid memory. What will likely happen is that it accesses the invalid memory anyway, and if that memory hasn't changed, you may get the old value. That's actually a bad thing, because it appears that the program is working as intended, when in reality it isn't.




            I am getting why I am getting output as 10 as we can see that memory
            holding that value is no longer persisting on heap?




            The memory is not valid anymore, but the number 10 may still be in that memory, and a.ref is still pointing to that memory. So even if the memory isn't valid, the 10 may still persist.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Jan 4 at 8:39

























            answered Jan 4 at 7:48









            BlazeBlaze

            7,6141832




            7,6141832

























                0














                What you have is undefined behavior because the program is accessing memory that does not belong to it anymore.
                delete frees the memory so that it can be reused, but that does not mean that value in that memory location is set to zero (if that is what you were expecting).






                share|improve this answer




























                  0














                  What you have is undefined behavior because the program is accessing memory that does not belong to it anymore.
                  delete frees the memory so that it can be reused, but that does not mean that value in that memory location is set to zero (if that is what you were expecting).






                  share|improve this answer


























                    0












                    0








                    0







                    What you have is undefined behavior because the program is accessing memory that does not belong to it anymore.
                    delete frees the memory so that it can be reused, but that does not mean that value in that memory location is set to zero (if that is what you were expecting).






                    share|improve this answer













                    What you have is undefined behavior because the program is accessing memory that does not belong to it anymore.
                    delete frees the memory so that it can be reused, but that does not mean that value in that memory location is set to zero (if that is what you were expecting).







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Jan 4 at 7:50









                    P.WP.W

                    18.7k41859




                    18.7k41859























                        0














                        It is because of Dangling pointer effect. Although we have deleted the memory data is not yet erased or not other data being stored over there and our pointer is still pointing to that memory.



                        for reference
                        https://www.geeksforgeeks.org/dangling-void-null-wild-pointers/






                        share|improve this answer




























                          0














                          It is because of Dangling pointer effect. Although we have deleted the memory data is not yet erased or not other data being stored over there and our pointer is still pointing to that memory.



                          for reference
                          https://www.geeksforgeeks.org/dangling-void-null-wild-pointers/






                          share|improve this answer


























                            0












                            0








                            0







                            It is because of Dangling pointer effect. Although we have deleted the memory data is not yet erased or not other data being stored over there and our pointer is still pointing to that memory.



                            for reference
                            https://www.geeksforgeeks.org/dangling-void-null-wild-pointers/






                            share|improve this answer













                            It is because of Dangling pointer effect. Although we have deleted the memory data is not yet erased or not other data being stored over there and our pointer is still pointing to that memory.



                            for reference
                            https://www.geeksforgeeks.org/dangling-void-null-wild-pointers/







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jan 4 at 9:31









                            Amit SharmaAmit Sharma

                            73




                            73






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54034897%2fc-scope-on-heap%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Monofisismo

                                Angular Downloading a file using contenturl with Basic Authentication

                                Olmecas