Alcott
Alcott

Reputation: 18585

put pointer in std::vector & memory leak

class A {
public:
    void foo()
    {
        char *buf = new char[10];
        vec.push_back(buf);
    }

private:
    vector<char *> vec;
};

int main()
{
    A a;
    a.foo();
    a.foo();
}

In class A, foo() allocates some memory and the pointer is saved to vec. When main() finishes, a will desconstruct, and so will a.vec, but will the allocated memory be released?

Upvotes: 1

Views: 466

Answers (2)

Bakery
Bakery

Reputation: 406

Or you could make a destructor

 ~A()
{
    for(unsigned int i =0; i < vec.size(); ++i)
         delete [] vec[i];
}

EDIT

As pointed out you need to make copy and assignment also (if you intend to use them that is)

class A
{
public:

    A& operator=(const A& other)
    {
        if(&other == this)
             return *this;

        DeepCopyFrom(other);

        return *this;
    }

    A(const A& other)
    {
        DeepCopyFrom(other);
    }


private:
    void DeepCopyFrom(const A& other) 
    {
        for(unsigned int i = 0; i < other.vec.size(); ++i) 
        {
            char* buff = new char[strlen(other.vec[i])];
            memcpy(buff, other.vec[i], strlen(other.vec[i]));
        }
    }

    std::vector<char*> vec;
};

More on the subject of deep copying and why you need it here

http://www.learncpp.com/cpp-tutorial/912-shallow-vs-deep-copying/

Upvotes: 2

ThirdOne
ThirdOne

Reputation: 1248

The memory will not be released. For it to be released, you need to put it in either a unique_ptr or a shared_ptr.

class A {
   public:
     void foo()
     {
        unique_ptr<char[]> buf(new char[10]);
        vec.push_back(buf);
     }
   private:
     vector<unique_ptr<char[]>> vec;
};

Upvotes: 4

Related Questions