Should I delete "new" object in a local function ?



  • Dear Sirs,

    I have a code as below:

    void MainWindow::on_pushButton_2_clicked()
    {
        QString *k = new QString;
    
        *k="H";
        delete k;      //Should I always do this ?
    }
    

    Should I always delete k before I leave the function?

    Thanks everyone.


  • Qt Champions 2016

    @Hiloshi
    Yes as k is not owned by anyone.

    However, why use new at all ?
    it will work just fine as

    QString k;



  • Yes, memory should always be collected when finished with it, especially if the object using it is no longer referenceable. For your example there should be no problem simply allocating a QString object type on the Stack, which is always preferable to Heap allocation when possible (for performance reasons and to prevent programmers from making mistakes causing memory leaks). That said, when Heap allocation is necessary I would avoid using raw pointers & delete directly if at all possible.

    A good rule of thumb is that if you're allocating on the Heap then it's best practice to pass your pointer to another object which will handle variable lifetime and cleanup for you. For simple data allocated strictly in a local context I would advise a smart pointer type. For your example specifically, I would consider using the QScopedPointer type, though in my personal opinion there are few times where QScopedPointer is truly useful given that it already implies the lifetime of your variable is fixed to a local scope and that it should therefore likely be placed on the Stack (one exception being locally allocated arrays with sizes known only at runtime).

    Example use of QScopedPointer:

    void MainWindow::on_pushButton_2_clicked()
    {
        QScopedPointer<QString> k(new QString);
        *k="H";
        ...
    }//scope closes, QScopedPointer runs destructor and invokes delete upon held ptr


  • Dear @mrjj , @corruptedsyntax ,

    Thanks for the help. For the QString example I provided is only for everyone easy understand.

    I have another question, in my example, if I run "pushButton_2" twice without delete k,
    will it occupy two physical memory ?



  • @Hiloshi said in Should I delete "new" object in a local function ?:

    example, if I run "p

    If you run twice and never delete then the following will happen:

    1.)  Enter function on_pushButton_2_clicked()
    2.)  QString is created on Heap
    3.)  k is set to QString's address
    4.)  QString pointed to by k is assigned new string value
    5.) a.)  exit function on_pushButton_2_clicked()
        b.)  pointer k on Stack is deallocated, but QString value it points to on Heap is NOT deallocated
        c.)  QString on heap persist existence, however there is no way in code to reference it or even
             know that it exist since we have lost the pointer to it
    6.)  At some future point, re-enter function on_pushButton_2_clicked()
    7.)  Create new QString on Heap (at this point there are 2 on Heap but 1 is not referenceable)
    continue...
    

    In short, the way the function is written (if you remove delete) you will create a new QString item everytime you enter the function and they will never be collected. If your program runs the function 500 times then there will be 500 unreachable strings remaining on the Heap.

    This can be a major problem if your program is intended to run indefinitely or run this function many times. In the past on 32-bit systems you might worry about running out of addressable space since 4GB of RAM was your limit. That's unlikely a real concern on modern 64-bit systems, but you will start seeing major performance drops as you continue making unneeded kernel calls for allocation and waste away all physical memory resources your system has, and don't get me started on how bad it'll be if these are all objects you unintentionally continue to render to a display.



  • Dear @corruptedsyntax ,

    Thank you very much. Now I can understand.

    Thanks.


  • Moderators

    Hi Hiloshi,

    There are very good Profiling and Memory Checking Tools that will detect memory leaks for you like Valgrind on Linux.
    When you use them you can experiment with different code approaches and see for yourself if there is something wrong with cleaning up your pointers.
    But if you have some concerns, don't hesitate to ask here on the forum. It's just a fun way of checking things yourself and learning by 'getting your hands dirty'.

    Happy coding,

    Eddy


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.