c++中内存泄漏的示例(通过使用异常)

Example of memory leak in c++ (by use of exceptions)

本文关键字:异常 内存 泄漏 c++      更新时间:2023-10-16

在C++如何编程中有一段话说:

一种常见的编程实践是分配动态内存,分配该内存指向一个指针,使用该指针操作内存并解除分配当不再需要内存时,使用delete来删除内存。如果在成功分配内存,但在delete语句执行之前,内存泄漏可能发生。C++标准在头中为提供类模板unique_ptr处理这种情况。

任何人都可以向我介绍一个真实的例子,异常发生,内存会像这篇文章一样泄漏吗?

一个更微妙的例子。

以一个包含两个动态分配数组的类的天真实现为例:

struct Foo {
private:
    int* first;
    int* second;
public:
    Foo()
        : first(new int[10000])
        , second(new int[10000])
    { }
    void Bar() { throw 42; }
    ~Foo()
    {
        delete [] first;
        delete [] second;
    }
};
int main()
{
    Foo f;
    /* more code */
}

现在,如果我们因为在某个地方调用方法Bar而得到异常,那么一切都很好——堆栈展开保证了f的析构函数被调用。

但是,如果我们在初始化second时得到一个bad_alloc,我们就会泄漏first指向的内存。

class MyClass
{
public:
    char* buffer;
    MyClass(bool throwException)
    {
        buffer = new char[1024];
        if(throwException)
            throw std::runtime_error("MyClass::MyClass() failed");
    }
    ~MyClass()
    {
        delete[] buffer;
    }
};

int main()
{
    // Memory leak, if an exception is thrown before a delete
    MyClass* ptr = new MyClass(false);
    throw std::runtime_error("<any error>");
    delete ptr;
}

int main()
{
    // Memory leak due to a missing call to MyClass()::~MyClass()
    // in case MyClass()::MyClass() throws an exception.
    MyClass instance = MyClass(true);
}

另请参阅:C++:如果构造函数可能抛出异常,则处理资源(参考FAQ17.4]

void func()
{
    char *p = new char[10];
    some_function_which_may_throw(p);
    delete [] p;
}

如果对some_function_which_may_throw(p)的调用引发异常,我们会泄漏p指向的内存。

的简单示例

try { 
  int* pValue = new int();
  if (someCondition) { 
    throw 42;
  }
  delete pValue;
} catch (int&) { 
}

为了有一个不那么做作的例子,我最近在用给定分配器对象分配节点时,在代码中发现了这种潜在的泄漏。

std::unique_ptr<node,alloc_aware> allocate_new_node(allocator& al, const value_type^ v) {
    char* buffer = al.allocate(sizeof(node)); //allocate memory
    return std::unique_ptr<node>(al.construct(buffer, v),{al})); //construct
}

由于缓冲区的原因,如何解决这个问题还不太明显,但在帮助下,我得到了它:

struct only_deallocate {
    allocator* a;    
    size_type s;
    only_deallocate(allocator& alloc, size_type size):a(&alloc), s(size) {}
    template<class T> void operator()(T* ptr) {a->deallocate(ptr, s);}
    operator alloc_aware() const {return alloc_aware(*a, s);}
};
std::unique_ptr<node,alloc_aware> allocate_new_node(allocator& al, const value_type& v) {
    std::unique_ptr<node, only_deallocate> buf(alloc.allocate(sizeof(node)),{alloc, sizeof(node)});//allocate memory
    alloc.construct(buf.get(), value);
    return std::unique_ptr<node,alloc_aware>(std::move(buf));
}

在此处编译代码