C++ : Coverity reports leaks for peculiar use of r

2019-08-14 05:32发布

问题:

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?