简体   繁体   English

使用Boehm GC时C ++中的内存泄漏的原因

[英]Cause of a memory leak in C++ when using the Boehm GC

This code is causing a memory leak for me, and I'm not sure why. 这段代码对我造成了内存泄漏,我不确定为什么。

[EDIT] Included code from here into question: [编辑] 此处包含的代码有疑问:

#include "src/base.cpp"

typedef std::map<std::string, AlObj*, std::less<std::string>, 
  gc_allocator<std::pair<const std::string, AlObj*> > > KWARG_TYPE;

AlInt::AlInt(int val)   {
    this->value = val;
    this->setup();
}

// attrs is of type KWARG_TYPE
void AlInt::setup() {
    this->attrs["__add__"] = new AddInts();
    this->attrs["__sub__"] = new SubtractInts();
    this->attrs["__mul__"] = new MultiplyInts();
    this->attrs["__div__"] = new DivideInts();
    this->attrs["__pow__"] = new PowerInts();
    this->attrs["__str__"] = new PrintInt();
}

int main() {
    while (true) {
        AlObj* a = new AlInt(3);
    }
}

AlInt inherits from AlObj, which in turn inherits from gc. AlInt继承自AlObj,而后者又继承自gc。 When I comment out the contents of setup() then I don't have a memory leak, this leads me to believe the issue is with the map not cleaning up, however I'm using the gc allocator, so I'm not sure where to look next. 当我注释掉setup()的内容时,没有内存泄漏,这使我相信问题在于映射未清除,但是我正在使用gc分配器,因此我不确定接下来要看的地方。 Thoughts? 思考?

The 'gc allocator' is allocating and looking after objects of this type: “ gc分配器”正在分配和照顾这种类型的对象:

std::pair<const std::string, AlObj*>

Just because this object has a pointer in it does not mean it the allocator will call delete on it. 仅仅因为该对象中有一个指针并不意味着它会在分配器上调用delete。

If you want the object created in setUp() to be GC then you need to allocate them via the GC. 如果要将setUp()中创建的对象作为GC,则需要通过GC分配它们。 Or learn to use boost:ptr_map or shared_ptr. 或学习使用boost:ptr_map或shared_ptr。

A map destroys (not deletes) the object it owns . 映射会销毁(而不是删除)其拥有的对象。 In this case it owns the pointer not what the pointer points at. 在这种情况下,它拥有指针, 而不是指针指向的指针。 So when the map is destroyed it deallocates everything associated with the map and the object it owns (for pointers this means it does nothing). 因此,在销毁地图时,它会取消分配与地图及其所拥有的对象关联的所有内容(对于指针,这意味着它什么也不做)。

If you have a map (or other container) that contains pointers. 如果您有一个包含指针的地图(或其他容器)。 You must manually delete the pointers otherwise there will be a memory leak. 您必须手动删除指针,否则会发生内存泄漏。 Alternatively you can use boost::ptr_map or a map that contains a share_ptr 或者,您可以使用boost :: ptr_map或包含share_ptr的地图

实质上,我要说的是,AlObj似乎已被破坏,但不是它的成员(因为除非我将内容放入attrs,否则它不会泄漏)。

The allocator is deleting your pairs. 分配器正在删除您的货币对。 But deleting a pair doesn't delete members of the pair that happen to be pointers. 但是删除一对并不会删除恰好是指针的一对成员。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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