简体   繁体   中英

C++ Local object goes out of scope returning a pointer (memory allocated using new). Memory leak because of this

There is a memory leak reported in this function. I'm not able to figure why this isn't freeing the memory?

Sample code:

void Somefunction(){
    Object1 * dangler = StaticClass::myFunc();
    /*...
      ...some processing using dangler
      ...*/
    delete dangler;
}

Object1* StaticClass::myFunc(){
    LocalObj lc;
    lc.another();
    return lc.get();
}

Class lc{
    Object1* m_dangler;
    void another(){
        m_danlger = new Object1();
    }
    Object1* get(){
        return m_danlger;
    }
}

This delete danlger; is not working and i'm seeing a memory leak at Object1 * dangler = StaticClass::myFunc();

The questions are: 1) Why am I not able to delete when the pointer danlger is indeed pointing to the location. 2) If this is not the correct way to free memory, where am I going wrong and what is the correct way?

The rule is surprisingly simple: every new must be balanced with a delete .

If your code doesn't balance these exactly then you have undefined behaviour or a memory leak. In your case that's trivial to check with your line by line debugger.

One of your problems with the lc class is that it's possible to copy it (using the compiler generated copy constructor) which will shallow copy the pointer member. It becomes difficult to track which object, if any, "owns" the memory allocated by another .

You could attempt to polish this class. But really, you may as well ditch the whole thing and use std::unique_ptr or std::shared_ptr instead, depending on your specific requirements. Those classes manage the delete for you and (unless you use them perversely) guarantee that new s and delete s are balanced.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM