Home > Mobile >  Memory leak with type vector<A>* in cpp
Memory leak with type vector<A>* in cpp

Time:09-28

Is there any memory leak in the below code section. I have a class A and a method that returns a pointer to vector of type A.

class A{
  public:
        shared_ptr<int> a;
};

vector<A>* _array(){
    // some code 
    return new vector<A>();
}

int main(){
    vector<A> *a = _array();
}

CodePudding user response:

Yes, in main() you assign what _array() allocates to *a but never free it. To fix it, you need to delete a;.

CodePudding user response:

Just remove the pointer.

class A{
  public:
        shared_ptr<int> a;
};

vector<A> _array(){
    // some code 
    return vector<A>();
}

int main(){
    vector<A> a = _array();
}

Not sure why you are using a pointer there, so I can't make any specific criticism, but probably the pointer is unnecessary. Most reasons given by newbies for using pointers are invalid.

Just realised I didn't answer the question. Yes there is a memory leak in your code. Arguably a harmless one, because the memory will be recovered when your program exits, but a leak nevertheless.

  • Related