Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Special Interest Groups
  3. C++ Gurus
  4. [solved] memory deallocation and the delete keyword

[solved] memory deallocation and the delete keyword

Scheduled Pinned Locked Moved C++ Gurus
25 Posts 7 Posters 22.9k Views
  • 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.
  • T Offline
    T Offline
    terietor
    wrote on 11 Aug 2011, 18:29 last edited by
    #1

    Hello,

    in some projects i have seen this way of deleting a pointer

    @MyClass *pointer;
    delete pointer;
    pointer=0;@

    why they do this?

    After the usage of the delete keyword there is no memory left why they give an invalid memory to the pointer?

    Instead of doing

    @delete pointer;@

    if i do

    @pointer = 0;@

    wiil i have the same result?

    thanks in advance

    terietor.gr

    1 Reply Last reply
    0
    • R Offline
      R Offline
      rokemoon
      wrote on 11 Aug 2011, 18:37 last edited by
      #2

      They do this cuz after @delete pointer;@ pointer points to the trash, so if you want to check the poiner in if section you need to set pointer to 0.
      @
      if (pointer) {
      //ok there we have alocated object
      } esle {
      //there we haven't alocated object
      //and can alocate there if need
      }
      @
      [quote]
      Instead of doing

      delete pointer;
      if i do

      pointer = 0;
      [/quote]
      If you set pointer to 0 you've get memory leak, cuz you lost pointer to the allocated memory.

      1 Reply Last reply
      0
      • M Offline
        M Offline
        mlong
        wrote on 11 Aug 2011, 18:38 last edited by
        #3

        No. It won't be the same result at all. A pointer simply holds a memory address which points to the start of an area of memory. It isn't the same as the object contained at that address, itself. Calling delete on a pointer frees the memory at that address, but the pointer still contains a (now-invalid) address. Setting the pointer back to 0 makes it obvious that the pointer is null.

        If an invalid pointer is dereferenced, there is undefined behavior as to what will happen. Sometimes things might silently continue to work, sometimes it fails in the most peculiar (or spectacular) ways. However, if a null pointer is dereferenced, the system will typically terminate with a Segmentation Fault (or some comparable memory error) which is pretty easy to track down.

        In short, setting the pointer back to 0 can make debugging a lot easier down the line. (But you need to delete the object contained there first!)

        Software Engineer
        My views and opinions do not necessarily reflect those of anyone -- living or dead, real or fictional -- in this universe or any other similar multiverse node. Void where prohibited. Your mileage may vary. Caveat emptor.

        1 Reply Last reply
        0
        • L Offline
          L Offline
          loladiro
          wrote on 11 Aug 2011, 18:39 last edited by
          #4

          NO!!
          @delete pointer@
          actually calls the destructor and releases the memory.
          Setting it equal to 0, would let the pointer point to the object at address 0 (your object will never be at address 0). If you don't call delete, the object will still exist in memory, but you can't access it anymore. Thus, you created a memory leak. Setting it equal to 0 after deleting is useful for checking whether the object exists. E.g.

          @
          if(someCondition)
          {
          delete pointer;
          pointer = 0;
          }

          //and later
          if(pointer)
          {
          //the object still exists, i.e. you can safely use it
          }else
          {
          //it doesn't, do something else
          }
          @

          1 Reply Last reply
          0
          • G Offline
            G Offline
            goetz
            wrote on 11 Aug 2011, 18:39 last edited by
            #5

            No, just setting the pointer to 0 does not delete the object.

            That's a good thing™!

            Assume the following code:

            @
            MyClass *pointer = new MyClass;

            MyClass *alias = pointer;
            alias = 0;

            pointer->doSomething();
            @

            The call to doSomething would fail, if the object had been deleted by assigning 0 to alias.

            Resetting the pointer to 0 after a delete can be a good practice in case the pointer can be accessed afterwards. If it had its previous value, using the pointer would lead to a segmentation fault, because the old object is no longer valid. To avoid a null pointer exception, you should check the pointer for being no-null of course :-)

            http://www.catb.org/~esr/faqs/smart-questions.html

            1 Reply Last reply
            0
            • M Offline
              M Offline
              mlong
              wrote on 11 Aug 2011, 18:45 last edited by
              #6

              Wow... this is definitely a hot-button issue! :-) I love the different details which accent each explanation of the core issue.

              Software Engineer
              My views and opinions do not necessarily reflect those of anyone -- living or dead, real or fictional -- in this universe or any other similar multiverse node. Void where prohibited. Your mileage may vary. Caveat emptor.

              1 Reply Last reply
              0
              • R Offline
                R Offline
                rokemoon
                wrote on 11 Aug 2011, 18:46 last edited by
                #7

                [quote author="mlong" date="1313088302"]Wow... this is definitely a hot-button issue! :-) I love the different details which accent each explanation of the core issue.[/quote]

                What explanation most liked? ;-)

                1 Reply Last reply
                0
                • L Offline
                  L Offline
                  loladiro
                  wrote on 11 Aug 2011, 18:48 last edited by
                  #8

                  [quote author="mlong" date="1313088302"]Wow... this is definitely a hot-button issue! :-) I love the different details which accent each explanation of the core issue.[/quote]

                  Indeed. When I was done typing there were already two other replies and 20sec later Volker's came to ;). At least one can say we are an active community. Where else do you get 4 elaborate answers within 10min?

                  1 Reply Last reply
                  0
                  • L Offline
                    L Offline
                    lgeyer
                    wrote on 11 Aug 2011, 18:49 last edited by
                    #9

                    In addition, deleting objects that already have been deleted result in an error, whereas deleting a null pointer does not. So setting the pointer to 0 after it has been deleted is good practice.
                    @
                    QObject* object = new QObject;

                    delete object; // OK

                    delete object; // FAIL

                    // ...

                    QObject* object = new QObject;

                    delete object; // OK
                    object = 0;

                    delete object; // OK
                    @

                    1 Reply Last reply
                    0
                    • R Offline
                      R Offline
                      rokemoon
                      wrote on 11 Aug 2011, 18:52 last edited by
                      #10

                      [quote author="loladiro" date="1313088523"]
                      Indeed. When I was done typing there were already two other replies and 20sec later Volker's came to ;). At least one can say we are an active community. Where else do you get 4 elaborate answers within 10min?[/quote]
                      For best frameworks best community :-)

                      1 Reply Last reply
                      0
                      • T Offline
                        T Offline
                        terietor
                        wrote on 11 Aug 2011, 18:59 last edited by
                        #11

                        thank you for your answers

                        so if i call delete and then allocate to 0,my pointer will point to an invalid address but i will have a mem leak.Correct?

                        So,if i call delete in my destructor there is no reason to allocate 0 to my pointer.Is that correct?

                        terietor.gr

                        1 Reply Last reply
                        0
                        • L Offline
                          L Offline
                          loladiro
                          wrote on 11 Aug 2011, 19:03 last edited by
                          #12

                          Summary:
                          @
                          pointer = 0;
                          @
                          Memory leak;

                          @
                          delete pointer;
                          @
                          No memory leak, but no way of detecting it was deleted (and, as Lukas pointed out, calling delete again will result in an error).

                          @
                          delete pointer;
                          pointer = 0;
                          @
                          No memory leak, you can check whether it still exists with if(pointer)

                          [quote]
                          So,if i call delete in my destructor there is no reason to allocate 0 to my pointer.Is that correct?
                          [/quote]
                          Correct (at least as long the pointer itself is not shared with other objects. Then it gets complicated)

                          1 Reply Last reply
                          0
                          • R Offline
                            R Offline
                            rokemoon
                            wrote on 11 Aug 2011, 19:04 last edited by
                            #13

                            You will have a leak if you set pointer to 0 and then delete it.
                            [quote author="Giorgos Tsiapaliwkas" date="1313089184"]
                            So,if i call delete in my destructor there is no reason to allocate 0 to my pointer.Is that correct?[/quote]
                            This is correct, cuz after destructor you will not need a pointer at all.

                            1 Reply Last reply
                            0
                            • M Offline
                              M Offline
                              mlong
                              wrote on 11 Aug 2011, 19:04 last edited by
                              #14

                              Rule of thumb:
                              If you need to delete something you have a pointer to:

                              • call delete first
                              • then set pointer to 0

                              Software Engineer
                              My views and opinions do not necessarily reflect those of anyone -- living or dead, real or fictional -- in this universe or any other similar multiverse node. Void where prohibited. Your mileage may vary. Caveat emptor.

                              1 Reply Last reply
                              0
                              • L Offline
                                L Offline
                                lgeyer
                                wrote on 11 Aug 2011, 19:08 last edited by
                                #15

                                If you create a new object using new a block of memory for this desired object is allocated (which means memory is taken from a large pool and reserved for this object) and the address of this memory block is stored to the pointer variable.

                                If you delete the object using delete the block of memory is returned to the memory pool and can be taken by another object. You pointer still points to the address of the memory where your object was previously stored. If you now access the object through this pointer your program will crash, as the object does no longer exist at this address in memory. This is why you should assign the address 0 the pointer, which indicates that this pointer does not address a valid block of memory.

                                You do not call delete within your destructor. If you call delete on an object the destructor for this is called by the delete operation.

                                [quote author="rokemoon" date="1313089462"]You will have a leak if you set pointer to 0 and then delete it.
                                [quote author="Giorgos Tsiapaliwkas" date="1313089184"]
                                So,if i call delete in my destructor there is no reason to allocate 0 to my pointer.Is that correct?[/quote]
                                This is correct, cuz after destructor you will not need a pointer at all.
                                [/quote]

                                No, you never ever call delete on the object which is currently destructed.

                                1 Reply Last reply
                                0
                                • R Offline
                                  R Offline
                                  rokemoon
                                  wrote on 11 Aug 2011, 19:08 last edited by
                                  #16

                                  And just for future read "this":http://doc.qt.nokia.com/latest/qscopedpointer.html and "this":http://doc.qt.nokia.com/latest/qsharedpointer.html. This will help you not to worry about manually deletion.

                                  1 Reply Last reply
                                  0
                                  • M Offline
                                    M Offline
                                    mlong
                                    wrote on 11 Aug 2011, 19:16 last edited by
                                    #17

                                    [quote author="rokemoon" date="1313089726"]And just for future read "this":http://doc.qt.nokia.com/latest/qscopedpointer.html and "this":http://doc.qt.nokia.com/latest/qsharedpointer.html. This will help you not to worry about manually deletion.[/quote]

                                    Caveat: Smart pointers are great tools to help manage the lifespan of objects, but they still require a base knowledge of what pointers are all about at their lowest level. It's important to make sure that you have a grasp of the fundamentals before using the higher-level counterparts, though. That's just IMHO, though.

                                    Software Engineer
                                    My views and opinions do not necessarily reflect those of anyone -- living or dead, real or fictional -- in this universe or any other similar multiverse node. Void where prohibited. Your mileage may vary. Caveat emptor.

                                    1 Reply Last reply
                                    0
                                    • G Offline
                                      G Offline
                                      goetz
                                      wrote on 11 Aug 2011, 19:20 last edited by
                                      #18

                                      [quote author="mlong" date="1313090165"]
                                      Caveat: Smart pointers are great tools to help manage the lifespan of objects, but they still require a base knowledge of what pointers are all about at their lowest level. It's important to make sure that you have a grasp of the fundamentals before using the higher-level counterparts, though. That's just IMHO, though.
                                      [/quote]

                                      I cannot but second this!
                                      So we have the outline for next year's "DevDays T-Shirts":http://developer.qt.nokia.com/forums/viewreply/50309/ :) :) :)

                                      http://www.catb.org/~esr/faqs/smart-questions.html

                                      1 Reply Last reply
                                      0
                                      • T Offline
                                        T Offline
                                        terietor
                                        wrote on 11 Aug 2011, 19:36 last edited by
                                        #19

                                        [quote author="Lukas Geyer" date="1313089715"]
                                        No, you never ever call delete on the object which is currently destructed.[/quote]

                                        if i have this

                                        @class a {
                                        private:
                                        BClass* pointer;
                                        };@

                                        then it is correct to do the following,right?

                                        @~a::a(){
                                        delete pointer;
                                        }@

                                        the follow is true or false?

                                        @delete pointer;
                                        pointer=0;

                                        if (pointer) {
                                        ....}@

                                        terietor.gr

                                        1 Reply Last reply
                                        0
                                        • G Offline
                                          G Offline
                                          giesbert
                                          wrote on 11 Aug 2011, 19:39 last edited by
                                          #20

                                          [quote author="Giorgos Tsiapaliwkas" date="1313091362"]

                                          if i have this

                                          @class a {
                                          private:
                                          BClass* pointer;
                                          };@

                                          then it is correct to do the following,right?

                                          @~a::a(){
                                          delete pointer;
                                          }@

                                          the follow is true or false?

                                          @delete pointer;
                                          pointer=0;

                                          if (pointer) {
                                          ....}@

                                          [/quote]

                                          @~a::a(){
                                          delete pointer;
                                          }@

                                          should be this

                                          @a::~a(){ // the ~ is not the class name it's parte of the function name
                                          delete pointer;
                                          }@

                                          the rest is ok.

                                          EDIT:
                                          Excurse: it's always

                                          • returntype classname::functionname(parameters)

                                          and constructors and destructors have no return type :-)

                                          Nokia Certified Qt Specialist.
                                          Programming Is Like Sex: One mistake and you have to support it for the rest of your life. (Michael Sinz)

                                          1 Reply Last reply
                                          0

                                          1/25

                                          11 Aug 2011, 18:29

                                          • Login

                                          • Login or register to search.
                                          1 out of 25
                                          • First post
                                            1/25
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • Users
                                          • Groups
                                          • Search
                                          • Get Qt Extensions
                                          • Unsolved