Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. Why this code doesn't crash?

Why this code doesn't crash?

Scheduled Pinned Locked Moved C / C++ / MFC
c++databasequestionlearning
14 Posts 6 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • C ComplexLifeForm

    Hi, Recently a friend of mine who is learning C++ wrote a code as given below class SingleTon { public: static SingleTon& GetInstance() { return *ptr; } private: static SingleTon* ptr; }; SingleTon* SingleTon::ptr = NULL; int _tmain() { SingleTon &ref = SingleTon::GetInstance(); if(&ref == NULL) { cout << "The reference is NULL"; } return 0; } My query is why didn't this code crashed. The program simply printed "The reference is NULL" and exited. I am a bit confused here, The pointer is initialized to NULL and in GetInstance() it is dereferenced. In my opinion as soon as it was dereferenced, the program should have crashed!! Or is there something basic I am missing? Thanks & Regards :confused: :confused:

    C Offline
    C Offline
    CPallini
    wrote on last edited by
    #2

    IMHO the pointer is never dereferenced in the above code. :)

    If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
    This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke

    1 Reply Last reply
    0
    • C ComplexLifeForm

      Hi, Recently a friend of mine who is learning C++ wrote a code as given below class SingleTon { public: static SingleTon& GetInstance() { return *ptr; } private: static SingleTon* ptr; }; SingleTon* SingleTon::ptr = NULL; int _tmain() { SingleTon &ref = SingleTon::GetInstance(); if(&ref == NULL) { cout << "The reference is NULL"; } return 0; } My query is why didn't this code crashed. The program simply printed "The reference is NULL" and exited. I am a bit confused here, The pointer is initialized to NULL and in GetInstance() it is dereferenced. In my opinion as soon as it was dereferenced, the program should have crashed!! Or is there something basic I am missing? Thanks & Regards :confused: :confused:

      T Offline
      T Offline
      toxcct
      wrote on last edited by
      #3

      probably because you tested in debug mode (where pointers are not actually initialized to 0x00000000). test in release mode and tell us if it still doesn't crash...

      [VisualCalc][Binary Guide][CommDialogs] | [Forums Guidelines]

      C C 2 Replies Last reply
      0
      • T toxcct

        probably because you tested in debug mode (where pointers are not actually initialized to 0x00000000). test in release mode and tell us if it still doesn't crash...

        [VisualCalc][Binary Guide][CommDialogs] | [Forums Guidelines]

        C Offline
        C Offline
        CPallini
        wrote on last edited by
        #4

        toxcct wrote:

        test in release mode and tell us if it still doesn't crash...

        I've done. It behaves exactly the same. :)

        If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
        This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke

        T 1 Reply Last reply
        0
        • T toxcct

          probably because you tested in debug mode (where pointers are not actually initialized to 0x00000000). test in release mode and tell us if it still doesn't crash...

          [VisualCalc][Binary Guide][CommDialogs] | [Forums Guidelines]

          C Offline
          C Offline
          ComplexLifeForm
          wrote on last edited by
          #5

          I had tested in Release mode as well, yet the program never crashed. I had used VC++ 2005 compiler with SP1 on Windows XP Pro + SP2 Thanks :confused:

          1 Reply Last reply
          0
          • C CPallini

            toxcct wrote:

            test in release mode and tell us if it still doesn't crash...

            I've done. It behaves exactly the same. :)

            If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
            This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke

            T Offline
            T Offline
            toxcct
            wrote on last edited by
            #6

            ok; it was just a guess, i have no compiler here. however, i don't really like the way the OP uses NULL. i'm not even sure a reference gets a NULL pointer "dereference"...

            [VisualCalc][Binary Guide][CommDialogs] | [Forums Guidelines]

            C 1 Reply Last reply
            0
            • T toxcct

              ok; it was just a guess, i have no compiler here. however, i don't really like the way the OP uses NULL. i'm not even sure a reference gets a NULL pointer "dereference"...

              [VisualCalc][Binary Guide][CommDialogs] | [Forums Guidelines]

              C Offline
              C Offline
              CPallini
              wrote on last edited by
              #7

              toxcct wrote:

              however, i don't really like the way the OP uses NULL

              I don't like too. Nonetheless, the address of operator seems to be legitimate on the reference. :)

              If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
              This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke

              1 Reply Last reply
              0
              • C ComplexLifeForm

                Hi, Recently a friend of mine who is learning C++ wrote a code as given below class SingleTon { public: static SingleTon& GetInstance() { return *ptr; } private: static SingleTon* ptr; }; SingleTon* SingleTon::ptr = NULL; int _tmain() { SingleTon &ref = SingleTon::GetInstance(); if(&ref == NULL) { cout << "The reference is NULL"; } return 0; } My query is why didn't this code crashed. The program simply printed "The reference is NULL" and exited. I am a bit confused here, The pointer is initialized to NULL and in GetInstance() it is dereferenced. In my opinion as soon as it was dereferenced, the program should have crashed!! Or is there something basic I am missing? Thanks & Regards :confused: :confused:

                D Offline
                D Offline
                Doc Lobster
                wrote on last edited by
                #8

                I dont think it should not crash at all unless you are trying to access or invoke any members of ref. (Though its technically very unlikely ;) to have an object at address 0x00 - its just an address like any other).

                1 Reply Last reply
                0
                • C ComplexLifeForm

                  Hi, Recently a friend of mine who is learning C++ wrote a code as given below class SingleTon { public: static SingleTon& GetInstance() { return *ptr; } private: static SingleTon* ptr; }; SingleTon* SingleTon::ptr = NULL; int _tmain() { SingleTon &ref = SingleTon::GetInstance(); if(&ref == NULL) { cout << "The reference is NULL"; } return 0; } My query is why didn't this code crashed. The program simply printed "The reference is NULL" and exited. I am a bit confused here, The pointer is initialized to NULL and in GetInstance() it is dereferenced. In my opinion as soon as it was dereferenced, the program should have crashed!! Or is there something basic I am missing? Thanks & Regards :confused: :confused:

                  R Offline
                  R Offline
                  Roger Stoltz
                  wrote on last edited by
                  #9

                  This is the beauty of references! It refers to an instance of an object at a certain address, it's not an actual instance of an object. In this case the address is NULL, which is perfectly legitimate. However, if you try to use any of its members it would of course crash since the 'this' pointer is NULL.

                  "It's supposed to be hard, otherwise anybody could do it!" - selfquote
                  "High speed never compensates for wrong direction!" - unknown

                  1 Reply Last reply
                  0
                  • C ComplexLifeForm

                    Hi, Recently a friend of mine who is learning C++ wrote a code as given below class SingleTon { public: static SingleTon& GetInstance() { return *ptr; } private: static SingleTon* ptr; }; SingleTon* SingleTon::ptr = NULL; int _tmain() { SingleTon &ref = SingleTon::GetInstance(); if(&ref == NULL) { cout << "The reference is NULL"; } return 0; } My query is why didn't this code crashed. The program simply printed "The reference is NULL" and exited. I am a bit confused here, The pointer is initialized to NULL and in GetInstance() it is dereferenced. In my opinion as soon as it was dereferenced, the program should have crashed!! Or is there something basic I am missing? Thanks & Regards :confused: :confused:

                    R Offline
                    R Offline
                    Rajkumar R
                    wrote on last edited by
                    #10

                    Deferencing is accesing value, indirectly through pointer. In your example I say it is not deferencing, its referencing. int val = *ptr; // accesses value; int &ref = *ptr; // don't accesses value;

                    int *ptr2 = &*ptr1;

                    // here Value of (*ptr1) is not accessed, as ptr2 is not going to store the address the temporary value (*ptr1), instead stores address itself (ptr1). similarly int &ref = *ptr; is not dereferencing the value but referencing the memory location; "A reference holds the address of an object, but behaves syntactically like an object." from msdn; int *ptr2 = &*ptr1; is same as int &ref = *ptr; check the code generated for the two expression. and "int *ptr1 = NULL; int *ptr2 = &*ptr1" also won't crash.

                    C 1 Reply Last reply
                    0
                    • R Rajkumar R

                      Deferencing is accesing value, indirectly through pointer. In your example I say it is not deferencing, its referencing. int val = *ptr; // accesses value; int &ref = *ptr; // don't accesses value;

                      int *ptr2 = &*ptr1;

                      // here Value of (*ptr1) is not accessed, as ptr2 is not going to store the address the temporary value (*ptr1), instead stores address itself (ptr1). similarly int &ref = *ptr; is not dereferencing the value but referencing the memory location; "A reference holds the address of an object, but behaves syntactically like an object." from msdn; int *ptr2 = &*ptr1; is same as int &ref = *ptr; check the code generated for the two expression. and "int *ptr1 = NULL; int *ptr2 = &*ptr1" also won't crash.

                      C Offline
                      C Offline
                      ComplexLifeForm
                      wrote on last edited by
                      #11

                      Not sure if this is applicable here. If you change the original class as class SingleTon { public: static SingleTon GetInstance() { return *ptr; } private: static SingleTon* ptr; }; SingleTon* SingleTon::ptr = NULL; int _tmain() { SingleTon ref = SingleTon::GetInstance(); if(&ref == NULL) { cout << "The reference is NULL"; } return 0; } The program still doesn't crash, but it doesn't prints anything since in this case &ref != NULL And even if I added another member function and accessed it through the "ref" variable, the program still didn't crashed in the release mode and in fact it gave me the correct values Thanks :confused: :confused:

                      R 1 Reply Last reply
                      0
                      • C ComplexLifeForm

                        Not sure if this is applicable here. If you change the original class as class SingleTon { public: static SingleTon GetInstance() { return *ptr; } private: static SingleTon* ptr; }; SingleTon* SingleTon::ptr = NULL; int _tmain() { SingleTon ref = SingleTon::GetInstance(); if(&ref == NULL) { cout << "The reference is NULL"; } return 0; } The program still doesn't crash, but it doesn't prints anything since in this case &ref != NULL And even if I added another member function and accessed it through the "ref" variable, the program still didn't crashed in the release mode and in fact it gave me the correct values Thanks :confused: :confused:

                        R Offline
                        R Offline
                        Rajkumar R
                        wrote on last edited by
                        #12

                        ahh, that is empty class, put data member. when you dereferencing no data is accessed in empty class. try this,

                        class SingleTon
                        {
                        char m_c;
                        public:
                        static SingleTon GetInstance()
                        {
                        return *ptr;
                        }
                        private:
                        static SingleTon* ptr;
                        };

                        it will crash and

                        class SingleTon
                        {
                        char m_c;
                        public:
                        static SingleTon& GetInstance()
                        {
                        return *ptr;
                        }
                        private:
                        static SingleTon* ptr;
                        };

                        it won't crash even with data member, my reply is applicable here also.

                        C 1 Reply Last reply
                        0
                        • R Rajkumar R

                          ahh, that is empty class, put data member. when you dereferencing no data is accessed in empty class. try this,

                          class SingleTon
                          {
                          char m_c;
                          public:
                          static SingleTon GetInstance()
                          {
                          return *ptr;
                          }
                          private:
                          static SingleTon* ptr;
                          };

                          it will crash and

                          class SingleTon
                          {
                          char m_c;
                          public:
                          static SingleTon& GetInstance()
                          {
                          return *ptr;
                          }
                          private:
                          static SingleTon* ptr;
                          };

                          it won't crash even with data member, my reply is applicable here also.

                          C Offline
                          C Offline
                          ComplexLifeForm
                          wrote on last edited by
                          #13

                          Thanks Rajkumar for the explaintion But I do have more queries. If I add a member method like this class SingleTon { char m_c; public: static SingleTon &GetInstance() { return *ptr; } std::string GetClassName() { return std::string("SingleTon Class"); } private: static SingleTon* ptr; }; and access it like this SingleTon& ref = SingleTon::GetInstance(); std::string className = ref.GetClassName(); cout << className.c_str(); The program doesn't crash and it prints the correct value. Can you please explain why it should print the correct value? Now we have a member variable also. Or is it the case that the since the method is not accessing the data member variable, it is not crashing and it is treated similar to empty class scenario? Thanks :confused::confused:

                          R 1 Reply Last reply
                          0
                          • C ComplexLifeForm

                            Thanks Rajkumar for the explaintion But I do have more queries. If I add a member method like this class SingleTon { char m_c; public: static SingleTon &GetInstance() { return *ptr; } std::string GetClassName() { return std::string("SingleTon Class"); } private: static SingleTon* ptr; }; and access it like this SingleTon& ref = SingleTon::GetInstance(); std::string className = ref.GetClassName(); cout << className.c_str(); The program doesn't crash and it prints the correct value. Can you please explain why it should print the correct value? Now we have a member variable also. Or is it the case that the since the method is not accessing the data member variable, it is not crashing and it is treated similar to empty class scenario? Thanks :confused::confused:

                            R Offline
                            R Offline
                            Rajkumar R
                            wrote on last edited by
                            #14

                            psychedelic_fur wrote:

                            Or is it the case that the since the method is not accessing the data member variable

                            yes, you can also do the similar code. (*(SingleTon *)0).functionAccessNoDataMember(); (*(SingleTon *)0).functionAccessDataMember(); // crashes calling a member function is not dereferencing, member function is called as if a normal function with storing the object address to register which is called this pointer, whenever a data member is accessed the this pointer is dereferenced like *(this + data member offset) // causes access violation if this pointer is not valid address. calling member function is not crashing because code is same for all instance of object and function pointer is same no need to call like (this + memberfunction)();

                            1 Reply Last reply
                            0
                            Reply
                            • Reply as topic
                            Log in to reply
                            • Oldest to Newest
                            • Newest to Oldest
                            • Most Votes


                            • Login

                            • Don't have an account? Register

                            • Login or register to search.
                            • First post
                              Last post
                            0
                            • Categories
                            • Recent
                            • Tags
                            • Popular
                            • World
                            • Users
                            • Groups