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. When to delete, and when to NULL?

When to delete, and when to NULL?

Scheduled Pinned Locked Moved C / C++ / MFC
performancequestion
17 Posts 10 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 Offline
    C Offline
    Chambers
    wrote on last edited by
    #1

    Hi all, I have got a little lost with regards to pointers. I think its quite simple (if you know the answer), basically I have some code like :

    void NewPointer()
    {
    if (m_pPointer == NULL)
    {
    m_pPointer = new(MyCPointClass)
    if (m_pPointer->NewPoint)
    return;
    else
    delete(m_pPointer);
    }
    }

    However, the pointer is deleted in this function, and then its deleted elsewhere in my program through a destructor (which is called when i exit the app). If the BOOL function NewPoint returns TRUE every time then everything is OK (my app doesn`t try to delete the same pointer twice). HOWEVER, it does if it returns FALSE. Basically I need to know if a memory leak would occur if I inserted : m_pPointer = NULL; instead of actually deleting it in the function? What actually happens to the memory allocated by new in this case? The reason I ask is because, although my program WOULD expel any memory leaks upon exiting the program, I don`t want them building up whilst I am running the damn thing, because in the end I could run out of memory. So, basically, what I need to know is, if I make the m_pPointer = NULL, will a memory leak occur, and why/why not? Thanks again guys for your intuition, Cheers, Alan.:) "When I left you I was but the learner, now I am the Master" - Darth Vader:mad:

    N J G C 4 Replies Last reply
    0
    • C Chambers

      Hi all, I have got a little lost with regards to pointers. I think its quite simple (if you know the answer), basically I have some code like :

      void NewPointer()
      {
      if (m_pPointer == NULL)
      {
      m_pPointer = new(MyCPointClass)
      if (m_pPointer->NewPoint)
      return;
      else
      delete(m_pPointer);
      }
      }

      However, the pointer is deleted in this function, and then its deleted elsewhere in my program through a destructor (which is called when i exit the app). If the BOOL function NewPoint returns TRUE every time then everything is OK (my app doesn`t try to delete the same pointer twice). HOWEVER, it does if it returns FALSE. Basically I need to know if a memory leak would occur if I inserted : m_pPointer = NULL; instead of actually deleting it in the function? What actually happens to the memory allocated by new in this case? The reason I ask is because, although my program WOULD expel any memory leaks upon exiting the program, I don`t want them building up whilst I am running the damn thing, because in the end I could run out of memory. So, basically, what I need to know is, if I make the m_pPointer = NULL, will a memory leak occur, and why/why not? Thanks again guys for your intuition, Cheers, Alan.:) "When I left you I was but the learner, now I am the Master" - Darth Vader:mad:

      N Offline
      N Offline
      Nish Nishant
      wrote on last edited by
      #2

      What you have new'd you must delete What you have new'd you must delete What you have new'd you must delete If you then make it null that's a good programming practice. but if you make it null without deleting it then you simply create a memory leak. Nish Sonork ID 100.9786 voidmain
      www.busterboy.org
      Nish is a BIG fan of Goran Ivanisevic

      1 Reply Last reply
      0
      • C Chambers

        Hi all, I have got a little lost with regards to pointers. I think its quite simple (if you know the answer), basically I have some code like :

        void NewPointer()
        {
        if (m_pPointer == NULL)
        {
        m_pPointer = new(MyCPointClass)
        if (m_pPointer->NewPoint)
        return;
        else
        delete(m_pPointer);
        }
        }

        However, the pointer is deleted in this function, and then its deleted elsewhere in my program through a destructor (which is called when i exit the app). If the BOOL function NewPoint returns TRUE every time then everything is OK (my app doesn`t try to delete the same pointer twice). HOWEVER, it does if it returns FALSE. Basically I need to know if a memory leak would occur if I inserted : m_pPointer = NULL; instead of actually deleting it in the function? What actually happens to the memory allocated by new in this case? The reason I ask is because, although my program WOULD expel any memory leaks upon exiting the program, I don`t want them building up whilst I am running the damn thing, because in the end I could run out of memory. So, basically, what I need to know is, if I make the m_pPointer = NULL, will a memory leak occur, and why/why not? Thanks again guys for your intuition, Cheers, Alan.:) "When I left you I was but the learner, now I am the Master" - Darth Vader:mad:

        J Offline
        J Offline
        Jon Sagara
        wrote on last edited by
        #3

        Nish answered your question, but here's a little debugging tip: When doing comparisons, put the constant value on the LHS of the comparison operator:if (NULL == m_pPointer)
        If you happen to accidentally leave off one of the equal signs (i.e., NULL = m_pPointer), your code won't compile because you can't assign a value to a literal. This has saved me lots of debugging headaches. :) Jon Sagara "We assume you already know not to consider something like Windows as a firewall platform. Does the name "Windows" evoke images of security? Silly rabbit, Windows is for desktops." -- Unix System Administration Handbook

        R J 2 Replies Last reply
        0
        • C Chambers

          Hi all, I have got a little lost with regards to pointers. I think its quite simple (if you know the answer), basically I have some code like :

          void NewPointer()
          {
          if (m_pPointer == NULL)
          {
          m_pPointer = new(MyCPointClass)
          if (m_pPointer->NewPoint)
          return;
          else
          delete(m_pPointer);
          }
          }

          However, the pointer is deleted in this function, and then its deleted elsewhere in my program through a destructor (which is called when i exit the app). If the BOOL function NewPoint returns TRUE every time then everything is OK (my app doesn`t try to delete the same pointer twice). HOWEVER, it does if it returns FALSE. Basically I need to know if a memory leak would occur if I inserted : m_pPointer = NULL; instead of actually deleting it in the function? What actually happens to the memory allocated by new in this case? The reason I ask is because, although my program WOULD expel any memory leaks upon exiting the program, I don`t want them building up whilst I am running the damn thing, because in the end I could run out of memory. So, basically, what I need to know is, if I make the m_pPointer = NULL, will a memory leak occur, and why/why not? Thanks again guys for your intuition, Cheers, Alan.:) "When I left you I was but the learner, now I am the Master" - Darth Vader:mad:

          G Offline
          G Offline
          Gert Boddaert
          wrote on last edited by
          #4

          void NewPointer() { if (m_pPointer == NULL) { m_pPointer = new(MyCPointClass); if (NULL != pPointer && m_pPointer->NewPoint()) // NewPoint is a function, right? { return; } else { delete(m_pPointer); m_pPointer = NULL; // avoid deleting the memory twice! deleting a NULL pointer is safe, but has a performance penalty since a call to the C-runtime library is done. } } } void DeletePointer() { if (NULL != m_pPointer) { delete m_pPointer; m_pPointer = NULL; } } if you insert m_pPointer = NULL somewhere in your code between NewPointer() and DeletePointer(), then yes you have a memory leak. -------------------------------------------------- If my messages appear curt, I apologize. I try to be brief to save your time as well as mine. --------------------------------------------------

          1 Reply Last reply
          0
          • J Jon Sagara

            Nish answered your question, but here's a little debugging tip: When doing comparisons, put the constant value on the LHS of the comparison operator:if (NULL == m_pPointer)
            If you happen to accidentally leave off one of the equal signs (i.e., NULL = m_pPointer), your code won't compile because you can't assign a value to a literal. This has saved me lots of debugging headaches. :) Jon Sagara "We assume you already know not to consider something like Windows as a firewall platform. Does the name "Windows" evoke images of security? Silly rabbit, Windows is for desktops." -- Unix System Administration Handbook

            R Offline
            R Offline
            Ray Kinsella
            wrote on last edited by
            #5

            Jon Sagara wrote: When doing comparisons, put the constant value on the LHS of the comparison operator: Quote/Unquote 'Debugging Windows Application' Microsoft Press ;) Regards Ray "Je Suis Mort De Rire"

            J 1 Reply Last reply
            0
            • J Jon Sagara

              Nish answered your question, but here's a little debugging tip: When doing comparisons, put the constant value on the LHS of the comparison operator:if (NULL == m_pPointer)
              If you happen to accidentally leave off one of the equal signs (i.e., NULL = m_pPointer), your code won't compile because you can't assign a value to a literal. This has saved me lots of debugging headaches. :) Jon Sagara "We assume you already know not to consider something like Windows as a firewall platform. Does the name "Windows" evoke images of security? Silly rabbit, Windows is for desktops." -- Unix System Administration Handbook

              J Offline
              J Offline
              Jim A Johnson
              wrote on last edited by
              #6

              Jon Sagara wrote: When doing comparisons, put the constant value on the LHS of the comparison operator: if (NULL == m_pPointer) If you happen to accidentally leave off one of the equal signs (i.e., NULL = m_pPointer), your code won't compile because you can't assign a value to a literal. Here's a better tip: Write it in the readable fashion, as you did, eg: if (m_pointer == NULL) and then use the following pragma to prevent assignments in the body of an if statement: #pragma warning(error : 4706) // Assignment in conditional This keeps your code readable and safe at the same time. And while the pragma is not portable, the resulting safe, readable code is.

              J 1 Reply Last reply
              0
              • R Ray Kinsella

                Jon Sagara wrote: When doing comparisons, put the constant value on the LHS of the comparison operator: Quote/Unquote 'Debugging Windows Application' Microsoft Press ;) Regards Ray "Je Suis Mort De Rire"

                J Offline
                J Offline
                Jon Sagara
                wrote on last edited by
                #7

                Yep, it's in there, too. :) Jon Sagara "We assume you already know not to consider something like Windows as a firewall platform. Does the name "Windows" evoke images of security? Silly rabbit, Windows is for desktops." -- Unix System Administration Handbook

                1 Reply Last reply
                0
                • J Jim A Johnson

                  Jon Sagara wrote: When doing comparisons, put the constant value on the LHS of the comparison operator: if (NULL == m_pPointer) If you happen to accidentally leave off one of the equal signs (i.e., NULL = m_pPointer), your code won't compile because you can't assign a value to a literal. Here's a better tip: Write it in the readable fashion, as you did, eg: if (m_pointer == NULL) and then use the following pragma to prevent assignments in the body of an if statement: #pragma warning(error : 4706) // Assignment in conditional This keeps your code readable and safe at the same time. And while the pragma is not portable, the resulting safe, readable code is.

                  J Offline
                  J Offline
                  Jon Sagara
                  wrote on last edited by
                  #8

                  Jim A. Johnson wrote: if (NULL == m_pPointer) I didn't realize that this was non-portable. It has worked for me using VC6 and the GNU compilers. Also, what is so difficult to read? I actually prefer this method because I know right away what the value of the variable is supposed to be. Jon Sagara "We assume you already know not to consider something like Windows as a firewall platform. Does the name "Windows" evoke images of security? Silly rabbit, Windows is for desktops." -- Unix System Administration Handbook

                  M J 2 Replies Last reply
                  0
                  • J Jon Sagara

                    Jim A. Johnson wrote: if (NULL == m_pPointer) I didn't realize that this was non-portable. It has worked for me using VC6 and the GNU compilers. Also, what is so difficult to read? I actually prefer this method because I know right away what the value of the variable is supposed to be. Jon Sagara "We assume you already know not to consider something like Windows as a firewall platform. Does the name "Windows" evoke images of security? Silly rabbit, Windows is for desktops." -- Unix System Administration Handbook

                    M Offline
                    M Offline
                    Michael Dunn
                    wrote on last edited by
                    #9

                    He meant the #pragma that disallows assignments in if conditions is non-portable. --Mike-- http://home.inreach.com/mdunn/ #include "witty_sig.h" :love: your :bob: with :vegemite: and :beer:

                    J 1 Reply Last reply
                    0
                    • C Chambers

                      Hi all, I have got a little lost with regards to pointers. I think its quite simple (if you know the answer), basically I have some code like :

                      void NewPointer()
                      {
                      if (m_pPointer == NULL)
                      {
                      m_pPointer = new(MyCPointClass)
                      if (m_pPointer->NewPoint)
                      return;
                      else
                      delete(m_pPointer);
                      }
                      }

                      However, the pointer is deleted in this function, and then its deleted elsewhere in my program through a destructor (which is called when i exit the app). If the BOOL function NewPoint returns TRUE every time then everything is OK (my app doesn`t try to delete the same pointer twice). HOWEVER, it does if it returns FALSE. Basically I need to know if a memory leak would occur if I inserted : m_pPointer = NULL; instead of actually deleting it in the function? What actually happens to the memory allocated by new in this case? The reason I ask is because, although my program WOULD expel any memory leaks upon exiting the program, I don`t want them building up whilst I am running the damn thing, because in the end I could run out of memory. So, basically, what I need to know is, if I make the m_pPointer = NULL, will a memory leak occur, and why/why not? Thanks again guys for your intuition, Cheers, Alan.:) "When I left you I was but the learner, now I am the Master" - Darth Vader:mad:

                      C Offline
                      C Offline
                      Chambers
                      wrote on last edited by
                      #10

                      I would just like to say thanks to everybody for their response, all the answers were superb. I just didn`t think to delete the pointer first and then assign it NULL, but everything fits perfectly in my head now. I wondered how the application could delete those pointers in my program that were unused, without any trouble and it was because I had assigned them all to NULL in the constructor! For some reason I thought delete, deleted the memory AND set it to NULL, thats why I couldn`t grasp how it was actually working. But thanks to everyone who wrote in, I am very grateful, Cheers, Alan.:-D P.S. I liked the tips too. Just when I think I seem to be mastering this language, someone comes along and goes "Here's a better way of going about it...", that always amazes me. Thanks for those too guys. "When I left you I was but the learner, now I am the Master" - Darth Vader:mad:

                      1 Reply Last reply
                      0
                      • M Michael Dunn

                        He meant the #pragma that disallows assignments in if conditions is non-portable. --Mike-- http://home.inreach.com/mdunn/ #include "witty_sig.h" :love: your :bob: with :vegemite: and :beer:

                        J Offline
                        J Offline
                        Jon Sagara
                        wrote on last edited by
                        #11

                        Context - The Mother of all Flame Wars. Thanks for the note Michael, Jon Sagara "We assume you already know not to consider something like Windows as a firewall platform. Does the name "Windows" evoke images of security? Silly rabbit, Windows is for desktops." -- Unix System Administration Handbook

                        1 Reply Last reply
                        0
                        • J Jon Sagara

                          Jim A. Johnson wrote: if (NULL == m_pPointer) I didn't realize that this was non-portable. It has worked for me using VC6 and the GNU compilers. Also, what is so difficult to read? I actually prefer this method because I know right away what the value of the variable is supposed to be. Jon Sagara "We assume you already know not to consider something like Windows as a firewall platform. Does the name "Windows" evoke images of security? Silly rabbit, Windows is for desktops." -- Unix System Administration Handbook

                          J Offline
                          J Offline
                          Jim A Johnson
                          wrote on last edited by
                          #12

                          Jon Sagara wrote: I didn't realize that this was non-portable. It has worked for me using VC6 and the GNU compilers That's not what I said. Read it again, please.

                          J 1 Reply Last reply
                          0
                          • J Jim A Johnson

                            Jon Sagara wrote: I didn't realize that this was non-portable. It has worked for me using VC6 and the GNU compilers That's not what I said. Read it again, please.

                            J Offline
                            J Offline
                            Jon Sagara
                            wrote on last edited by
                            #13

                            This keeps your code readable and safe at the same time. And while the pragma is not portable, the resulting safe, readable code is. Misunderstanding. My bad. Please forgive me this one transgression. ;P Just out of curiosity, why don't you consider if (NULL == m_pPointer) readable? I admit it looked strange to me at first, but it's such a simple coding trick that you can use to save debugging time without having to remember some obscure pragma directive. Jon Sagara "We assume you already know not to consider something like Windows as a firewall platform. Does the name "Windows" evoke images of security? Silly rabbit, Windows is for desktops." -- Unix System Administration Handbook

                            T 1 Reply Last reply
                            0
                            • J Jon Sagara

                              This keeps your code readable and safe at the same time. And while the pragma is not portable, the resulting safe, readable code is. Misunderstanding. My bad. Please forgive me this one transgression. ;P Just out of curiosity, why don't you consider if (NULL == m_pPointer) readable? I admit it looked strange to me at first, but it's such a simple coding trick that you can use to save debugging time without having to remember some obscure pragma directive. Jon Sagara "We assume you already know not to consider something like Windows as a firewall platform. Does the name "Windows" evoke images of security? Silly rabbit, Windows is for desktops." -- Unix System Administration Handbook

                              T Offline
                              T Offline
                              Tim Smith
                              wrote on last edited by
                              #14

                              Yeah, I agree. It is all about just getting use to it. Tim Smith Descartes Systems Sciences, Inc.

                              C 1 Reply Last reply
                              0
                              • T Tim Smith

                                Yeah, I agree. It is all about just getting use to it. Tim Smith Descartes Systems Sciences, Inc.

                                C Offline
                                C Offline
                                Colin Urquhart
                                wrote on last edited by
                                #15

                                Why not use: if (!m_pPointer) instead of if (NULL == m_pPointer) :-)

                                M realJSOPR 2 Replies Last reply
                                0
                                • C Colin Urquhart

                                  Why not use: if (!m_pPointer) instead of if (NULL == m_pPointer) :-)

                                  M Offline
                                  M Offline
                                  Michael Dunn
                                  wrote on last edited by
                                  #16

                                  Because the second is instantly readable, whereas with the first one you have to remember that "!pointer" means "pointer is not zero". --Mike-- http://home.inreach.com/mdunn/ #include "witty_sig.h" :love: your :bob: with :vegemite: and :beer:

                                  1 Reply Last reply
                                  0
                                  • C Colin Urquhart

                                    Why not use: if (!m_pPointer) instead of if (NULL == m_pPointer) :-)

                                    realJSOPR Offline
                                    realJSOPR Offline
                                    realJSOP
                                    wrote on last edited by
                                    #17

                                    I agree with Mike, but I would make it

                                    if (m_pPointer == NULL)

                                    instead. It just looks better to me because it flows more like the way you speak the same phrase. I've never heard anyone say "If NULL is the pointer...", but instead, people say "If the pointer is NULL...". "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

                                    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