gpt4 book ai didi

C++ : Coverity reports leaks for peculiar use of references and containers

转载 作者:行者123 更新时间:2023-11-30 01:12:13 24 4
gpt4 key购买 nike

Coverity 报告以下代码的泄漏。我想要一些帮助来理解错误并重写此代码以消除错误。(错误在下面的代码中被注释为注释)

int main()
{
...
B* b = ...
// (1) Coverity: Storage is returned from
// allocation function operator new
// (2) Coverity: Assigning ...
A* a = new A();

// (3) Coverity: noescape: Resource a is not freed
// or pointed-to in add_a_to_b
b->add_a_to_b( *a );
...

// (4) Coverity: Resource leak: Variable a going out
// of scope leaks the storage it points to.
}

class B {
public:
std::vector<A> a_vector;
void add_a_to_b( const A& a )
{
a_vector.push_back( a );
}

-- 编辑 ---

我有一个关于 B::add_a_to_b 函数的特殊问题,这可能反射(reflect)了我对引用的不完整理解:a_vector 存储对 A 的引用还是创建传递给 add_a_to_b 的对象的拷贝?

最佳答案

您有内存泄漏,因为您调用了 new 而没有调用 delete。此外,您没有理由调用 new 或动态分配。您可以简单地自动分配 a。这同样适用于 b

B b;
A a;

...
b.add_a_to_b(a); // b stores a copy of `a`.

关于C++ : Coverity reports leaks for peculiar use of references and containers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34599022/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com