简体   繁体   中英

Deque Pointer Memory Leak

I have a struct in which i have used std::deque

class VariantWrapper;
typedef _STL_NAMESPACE_::deque<VariantWrapper> VariantQueue;

struct AttributeValueWrapper
{
AttributeValueWrapper() : bAttributeIsArray(false)
{
    pVariantQueue = new VariantQueue;
    if(!pVariantQueue)
        throw std::bad_alloc();
}
AttributeValueWrapper(const AttributeValueWrapper& a)
{
    pVariantQueue = a.TakeOwner();
    bAttributeIsArray = a.bAttributeIsArray;
}
AttributeValueWrapper& operator=(AttributeValueWrapper& r)
{
    throw std::bad_exception("equal operator not supported in AttributeValueWrapper");
}
VariantQueue* TakeOwner() const
{
    VariantQueue *p = pVariantQueue;
    pVariantQueue = NULL;
    return p;
}
~AttributeValueWrapper()
{
    if (pVariantQueue)
    {
        delete pVariantQueue;
    }

}

bool bAttributeIsArray;
mutable VariantQueue *pVariantQueue;};

Main Method:

int main()
{
 AttributeValueWrapper attrib;
}

I am running this code under Dr Memory (This is just a piece of code , project is quite big) and Dr Memory showing a memory leak at pVariantQueue = new VariantQueue inside the default constructor as:

Error #46: LEAK 8 direct bytes + 324 indirect bytes replace_operator_new d:\\drmemory_package\\common\\alloc_replace.c(2899): std::_Allocate<> ??:0 std::allocator<>::allocate ??:0 std::_Wrap_alloc<>::allocate ??:0 std::_Deque_alloc<>::_Alloc_proxy ??:0 std::_Deque_alloc<>::_Deque_alloc<> ??:0 std::deque<>::deque<> ??:0 AttributeValueWrapper::AttributeValueWrapper

Please share you thoughts on this issue.

I have also tried using std::unique_ptr , but still getting the same memory leak at same line no(same point):

struct AttributeValueWrapper
{
AttributeValueWrapper() : bAttributeIsArray(false)
{
    pVariantQueue = std::make_unique<VariantQueue>(new VariantQueue);
    if(!pVariantQueue)
        throw std::bad_alloc();
}
AttributeValueWrapper(const AttributeValueWrapper& a)
{
    pVariantQueue = a.TakeOwner();
    bAttributeIsArray = a.bAttributeIsArray;
}
AttributeValueWrapper& operator=(AttributeValueWrapper& r)
{
    throw std::bad_exception("equal operator not supported in AttributeValueWrapper");
}
std::unique_ptr<VariantQueue> TakeOwner() const
{
    std::unique_ptr<VariantQueue> p = std::move(pVariantQueue);
    pVariantQueue = NULL;
    return p;
}

~AttributeValueWrapper()
{

}

bool bAttributeIsArray;
mutable std::unique_ptr<VariantQueue> pVariantQueue;

};

Now getting memory leak at

pVariantQueue = std::make_unique<VariantQueue>(new VariantQueue);

Vinay

Your memory leak can most likely be found in the destructor. What happens to the objects in the queue when the queue goes away?

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