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 a pointer (C++)...

When to delete a pointer (C++)...

Scheduled Pinned Locked Moved C / C++ / MFC
c++performancetutorialquestion
16 Posts 12 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.
  • D DanielSheets

    I know that if you allocate an object on the heap using 'new', it needs to be deleted. But what if it's a function that returns a pointer to an object? For example...

    SomeClass *someClass = aFunction(); // aFunction returns a pointer to SomeClass.

    I'm assuming that inside of aFunction(), there is a 'new Someclass()' in there somewhere. However... When I delete someClass on app exit, the app crashes. If I comment out the delete, it exits ok. But won't there be a memory leak if someClass isn't deleted?

    C Offline
    C Offline
    Chris Losinger
    wrote on last edited by
    #2

    it's impossible to say. is aFunction returning a pointer to a global, or to an object that is it managing somehow ?

    image processing toolkits | batch image processing

    1 Reply Last reply
    0
    • D DanielSheets

      I know that if you allocate an object on the heap using 'new', it needs to be deleted. But what if it's a function that returns a pointer to an object? For example...

      SomeClass *someClass = aFunction(); // aFunction returns a pointer to SomeClass.

      I'm assuming that inside of aFunction(), there is a 'new Someclass()' in there somewhere. However... When I delete someClass on app exit, the app crashes. If I comment out the delete, it exits ok. But won't there be a memory leak if someClass isn't deleted?

      O Offline
      O Offline
      Orjan Westin
      wrote on last edited by
      #3

      Don't assume that a pointer you get has been created with new. Read the code, or documentation, to find out what your responsibilities are. It might have been created with new, in which case you need to call delete when you are done with it. It might have been created with malloc (or one of its relatives), in which case you need to call free when you are done with it. It might point to a global or static piece of data, in which case you don't release it. Never assume when it comes to memory management. In this case, it seems likely you do not need to release the pointer, but the only way to be sure is to read up on how it is created and what your responsibilities are.

      1 Reply Last reply
      0
      • D DanielSheets

        I know that if you allocate an object on the heap using 'new', it needs to be deleted. But what if it's a function that returns a pointer to an object? For example...

        SomeClass *someClass = aFunction(); // aFunction returns a pointer to SomeClass.

        I'm assuming that inside of aFunction(), there is a 'new Someclass()' in there somewhere. However... When I delete someClass on app exit, the app crashes. If I comment out the delete, it exits ok. But won't there be a memory leak if someClass isn't deleted?

        D Offline
        D Offline
        David Crow
        wrote on last edited by
        #4

        DanielSheets wrote:

        However... When I delete someClass on app exit, the app crashes.

        At any point do you reassign or increment someClass such that it points to a different location? For example:

        SomeClass *someClass = new SomeClass();
        someClass++;
        delete someClass; // will crash

        "One man's wage rise is another man's price increase." - Harold Wilson

        "Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons

        "You can easily judge the character of a man by how he treats those who can do nothing for him." - James D. Miles

        1 Reply Last reply
        0
        • D DanielSheets

          I know that if you allocate an object on the heap using 'new', it needs to be deleted. But what if it's a function that returns a pointer to an object? For example...

          SomeClass *someClass = aFunction(); // aFunction returns a pointer to SomeClass.

          I'm assuming that inside of aFunction(), there is a 'new Someclass()' in there somewhere. However... When I delete someClass on app exit, the app crashes. If I comment out the delete, it exits ok. But won't there be a memory leak if someClass isn't deleted?

          F Offline
          F Offline
          Freak30
          wrote on last edited by
          #5

          Try deleting the pointer immediately after you receive it. Maybe it's deletetd inbetween and not set to null (bad practice), in which case a second delete would lead to a crash. Also check if the function is in a different dll, especially one loaded manually at runtime (i.e. not automatically at program start). In that case the dll could already be unloaded when you try to delete the pointer. Or the dll could be built in a different version of the compiler. If that is the case you may need to delete the pointer inside the dll. On a more general note: Deleting a pointer on app exit doesn't make much sense, except if you need it for the whole lifetime of your application. Typically you should delete it as soon as you don't need it anymore.

          The good thing about pessimism is, that you are always either right or pleasently surprised.

          S 1 Reply Last reply
          0
          • D DanielSheets

            I know that if you allocate an object on the heap using 'new', it needs to be deleted. But what if it's a function that returns a pointer to an object? For example...

            SomeClass *someClass = aFunction(); // aFunction returns a pointer to SomeClass.

            I'm assuming that inside of aFunction(), there is a 'new Someclass()' in there somewhere. However... When I delete someClass on app exit, the app crashes. If I comment out the delete, it exits ok. But won't there be a memory leak if someClass isn't deleted?

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

            DanielSheets wrote:

            aFunction()

            You should have the documentation (or the source code) of aFunction in order to know what to do.

            THESE PEOPLE REALLY BOTHER ME!! How can they know what you should do without knowing what you want done?!?! -- C++ FQA Lite

            1 Reply Last reply
            0
            • D DanielSheets

              I know that if you allocate an object on the heap using 'new', it needs to be deleted. But what if it's a function that returns a pointer to an object? For example...

              SomeClass *someClass = aFunction(); // aFunction returns a pointer to SomeClass.

              I'm assuming that inside of aFunction(), there is a 'new Someclass()' in there somewhere. However... When I delete someClass on app exit, the app crashes. If I comment out the delete, it exits ok. But won't there be a memory leak if someClass isn't deleted?

              D Offline
              D Offline
              DanielSheets
              wrote on last edited by
              #7

              Thanks for the replies. All of them helped to shed light on the subject for me. This is for a project being done with Qt. The documentation doesn't mention much about it (I couldn't find it anyway). I do have the source code though. Thanks again.

              D S A 3 Replies Last reply
              0
              • D DanielSheets

                Thanks for the replies. All of them helped to shed light on the subject for me. This is for a project being done with Qt. The documentation doesn't mention much about it (I couldn't find it anyway). I do have the source code though. Thanks again.

                D Offline
                D Offline
                Derek Tortonian
                wrote on last edited by
                #8

                A pointer is merely an address. In 32-bit Windows, it is a DWORD value. It's not even guaranteed that the address is valid, or that some data exists at that address. A safe way to 'delete' your pointer, is just to assign it a value of zero. That way, you can check first before attempting to use it.

                1 Reply Last reply
                0
                • F Freak30

                  Try deleting the pointer immediately after you receive it. Maybe it's deletetd inbetween and not set to null (bad practice), in which case a second delete would lead to a crash. Also check if the function is in a different dll, especially one loaded manually at runtime (i.e. not automatically at program start). In that case the dll could already be unloaded when you try to delete the pointer. Or the dll could be built in a different version of the compiler. If that is the case you may need to delete the pointer inside the dll. On a more general note: Deleting a pointer on app exit doesn't make much sense, except if you need it for the whole lifetime of your application. Typically you should delete it as soon as you don't need it anymore.

                  The good thing about pessimism is, that you are always either right or pleasently surprised.

                  S Offline
                  S Offline
                  Stefan_Lang
                  wrote on last edited by
                  #9

                  Freak30 wrote:

                  Also check if the function is in a different dll, especially one loaded manually at runtime (i.e. not automatically at program start). In that case the dll could already be unloaded when you try to delete the pointer. Or the dll could be built in a different version of the compiler. If that is the case you may need to delete the pointer inside the dll.

                  Actually, if the pointer points to memory allocated in a different DLL, that memory can only be safely deallocated through that DLL! That would be bad design, but maybe the DLL provides some Release function for that purpose.

                  Freak30 wrote:

                  On a more general note: Deleting a pointer on app exit doesn't make much sense,

                  I don't quite agree. Calling delete does more than just free memory. E. g. a the destructor of a file class might be implemented to flush the buffers and close the file properly. Not calling it would cause data loss! Other examples could be objects that stream data to the display or sound card: not closing them down properly may result in nasty artifacts. or think of a web connection to your bank account - do you want to leave it open?

                  GOTOs are a bit like wire coat hangers: they tend to breed in the darkness, such that where there once were few, eventually there are many, and the program's architecture collapses beneath them. (Fran Poretto)

                  F 1 Reply Last reply
                  0
                  • D DanielSheets

                    Thanks for the replies. All of them helped to shed light on the subject for me. This is for a project being done with Qt. The documentation doesn't mention much about it (I couldn't find it anyway). I do have the source code though. Thanks again.

                    S Offline
                    S Offline
                    Stefan_Lang
                    wrote on last edited by
                    #10

                    Typically, well designed API functions (like those from QT) will not pass pointers to allocated memory and expect you to free it - unless the function is specifically designed to do just that. For the reasons pointed out above, that would be bad design. In such cases, a better design would be to either return a container object by value, or a smart pointer (which, in a way, is also a kind of container), or the caller must pass a buffer to the function to hold the returned data - in which case both the allocation and deallocation are in the responsibility of the caller.

                    GOTOs are a bit like wire coat hangers: they tend to breed in the darkness, such that where there once were few, eventually there are many, and the program's architecture collapses beneath them. (Fran Poretto)

                    1 Reply Last reply
                    0
                    • D DanielSheets

                      I know that if you allocate an object on the heap using 'new', it needs to be deleted. But what if it's a function that returns a pointer to an object? For example...

                      SomeClass *someClass = aFunction(); // aFunction returns a pointer to SomeClass.

                      I'm assuming that inside of aFunction(), there is a 'new Someclass()' in there somewhere. However... When I delete someClass on app exit, the app crashes. If I comment out the delete, it exits ok. But won't there be a memory leak if someClass isn't deleted?

                      J Offline
                      J Offline
                      Joe Woodbury
                      wrote on last edited by
                      #11

                      Be aware that in Qt, you don't always have to delete/free a pointer. When you add widgets, for example, the parent object takes ownership. I suspect that is the case here. (Moreover, you could argue that not freeing memory on exit isn't a leak since the entire process is going away and the applications heap will be deleted.)

                      1 Reply Last reply
                      0
                      • D DanielSheets

                        Thanks for the replies. All of them helped to shed light on the subject for me. This is for a project being done with Qt. The documentation doesn't mention much about it (I couldn't find it anyway). I do have the source code though. Thanks again.

                        A Offline
                        A Offline
                        Albert Holguin
                        wrote on last edited by
                        #12

                        I've found the Qt documentation isn't all that great. The documentation for the MS frameworks is actually surprisingly good in comparison.

                        1 Reply Last reply
                        0
                        • S Stefan_Lang

                          Freak30 wrote:

                          Also check if the function is in a different dll, especially one loaded manually at runtime (i.e. not automatically at program start). In that case the dll could already be unloaded when you try to delete the pointer. Or the dll could be built in a different version of the compiler. If that is the case you may need to delete the pointer inside the dll.

                          Actually, if the pointer points to memory allocated in a different DLL, that memory can only be safely deallocated through that DLL! That would be bad design, but maybe the DLL provides some Release function for that purpose.

                          Freak30 wrote:

                          On a more general note: Deleting a pointer on app exit doesn't make much sense,

                          I don't quite agree. Calling delete does more than just free memory. E. g. a the destructor of a file class might be implemented to flush the buffers and close the file properly. Not calling it would cause data loss! Other examples could be objects that stream data to the display or sound card: not closing them down properly may result in nasty artifacts. or think of a web connection to your bank account - do you want to leave it open?

                          GOTOs are a bit like wire coat hangers: they tend to breed in the darkness, such that where there once were few, eventually there are many, and the program's architecture collapses beneath them. (Fran Poretto)

                          F Offline
                          F Offline
                          Freak30
                          wrote on last edited by
                          #13

                          Stefan_Lang wrote:

                          Freak30 wrote:

                          On a more general note: Deleting a pointer on app exit doesn't make much sense,

                          I don't quite agree. Calling delete does more than just free memory. E. g. a the destructor of a file class might be implemented to flush the buffers and close the file properly. Not calling it would cause data loss! Other examples could be objects that stream data to the display or sound card: not closing them down properly may result in nasty artifacts. or think of a web connection to your bank account - do you want to leave it open?

                          You conveniently left the conditional part of my sentence out of the quote. If you e.g. have a text editor application that only allows opening one file at the time and the only way to close the file is by closing the application, of course you need to delete the file object on application exit. But if you had an editor that can keep open multiple files at once and one of the files is closed, would you keep the object for this file active and delete it on application exit? I would delete it as soon as the file is closed. So my intention wasn't to say that you should never delete a pointer on appliaction exit. I wanted to say that it isn't a good idea to keep every pointer and delete all ofthem on application exit.

                          The good thing about pessimism is, that you are always either right or pleasently surprised.

                          S 1 Reply Last reply
                          0
                          • F Freak30

                            Stefan_Lang wrote:

                            Freak30 wrote:

                            On a more general note: Deleting a pointer on app exit doesn't make much sense,

                            I don't quite agree. Calling delete does more than just free memory. E. g. a the destructor of a file class might be implemented to flush the buffers and close the file properly. Not calling it would cause data loss! Other examples could be objects that stream data to the display or sound card: not closing them down properly may result in nasty artifacts. or think of a web connection to your bank account - do you want to leave it open?

                            You conveniently left the conditional part of my sentence out of the quote. If you e.g. have a text editor application that only allows opening one file at the time and the only way to close the file is by closing the application, of course you need to delete the file object on application exit. But if you had an editor that can keep open multiple files at once and one of the files is closed, would you keep the object for this file active and delete it on application exit? I would delete it as soon as the file is closed. So my intention wasn't to say that you should never delete a pointer on appliaction exit. I wanted to say that it isn't a good idea to keep every pointer and delete all ofthem on application exit.

                            The good thing about pessimism is, that you are always either right or pleasently surprised.

                            S Offline
                            S Offline
                            Stefan_Lang
                            wrote on last edited by
                            #14

                            My point was different from yours - I was focusing on the misguided perception some people (not you) might have that the whole point of delete is freeing memory. Specifically programmers coming from C and used to malloc/free might not consider it worthwhile deleting every leftover object upon exiting an application because of that. I pointed out why this would be a mistake that could lead to problems beyond the lifetime of the program. I do agree that any object allocated on the heap should be released (with delete) as soon as possible and not be kept around for longer than necessary. That is not what I understood from your statement though. Thanks for the clarification.

                            GOTOs are a bit like wire coat hangers: they tend to breed in the darkness, such that where there once were few, eventually there are many, and the program's architecture collapses beneath them. (Fran Poretto)

                            E 1 Reply Last reply
                            0
                            • S Stefan_Lang

                              My point was different from yours - I was focusing on the misguided perception some people (not you) might have that the whole point of delete is freeing memory. Specifically programmers coming from C and used to malloc/free might not consider it worthwhile deleting every leftover object upon exiting an application because of that. I pointed out why this would be a mistake that could lead to problems beyond the lifetime of the program. I do agree that any object allocated on the heap should be released (with delete) as soon as possible and not be kept around for longer than necessary. That is not what I understood from your statement though. Thanks for the clarification.

                              GOTOs are a bit like wire coat hangers: they tend to breed in the darkness, such that where there once were few, eventually there are many, and the program's architecture collapses beneath them. (Fran Poretto)

                              E Offline
                              E Offline
                              Erik Westermann
                              wrote on last edited by
                              #15

                              Stefan_Lang wrote:

                              I pointed out why this would be a mistake that could lead to problems beyond the lifetime of the program.

                              Yes, great point!

                              Erik Westermann

                              1 Reply Last reply
                              0
                              • D DanielSheets

                                I know that if you allocate an object on the heap using 'new', it needs to be deleted. But what if it's a function that returns a pointer to an object? For example...

                                SomeClass *someClass = aFunction(); // aFunction returns a pointer to SomeClass.

                                I'm assuming that inside of aFunction(), there is a 'new Someclass()' in there somewhere. However... When I delete someClass on app exit, the app crashes. If I comment out the delete, it exits ok. But won't there be a memory leak if someClass isn't deleted?

                                S Offline
                                S Offline
                                Satya Chamakuri
                                wrote on last edited by
                                #16

                                Hi, I think this may help you to get clarification, please see once. :) class student { int x; public: student() { x=0; } ~student() { cout<<"I am in student destructor\n"; } }; student* fun() { student *s = new student(); return s; } int main() { student *s = fun(); delete s; getchar(); return 0; }

                                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