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

末鹿安然 提交于 2019-12-11 12:11:20

问题


Coverity reports leaks for the following code. I would like some help understanding the errors and to re-write this code to be error free. ( The errors are annotated as comments in the code below )

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 );
    }

-- EDIT ---

I had a particular question about the B::add_a_to_b function, and this reflects my incomplete understanding of references perhaps: Does a_vector store a reference to A or does it create a copy of the object passed to add_a_to_b?


回答1:


You have a memory leak because you called new and you don't call delete. Furthermore, there is no reason for you to call new or allocate dynamically. You can simply allocate a automatically. The same applies to b.

B b;
A a;

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



回答2:


Well. You allocate memory for a, but you never use delete.

For every new there must be one delete.

delete a; // Do this when you don't need a anymore.

You can also do this - a = nullptr; to avoid a dangling pointer.

Edit:

You should learn how to use smart pointers. They're fairly easy to learn and you wouldnt have to worry about using new and delete, it'll take care of the delete.

Read this - Wiki & What is a smart pointer and when should I use one?



来源:https://stackoverflow.com/questions/34599022/c-coverity-reports-leaks-for-peculiar-use-of-references-and-containers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!