Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid memory leaks when using a vector of pointers to dynamically allocated objects in C++?

I'm using a vector of pointers to objects. These objects are derived from a base class, and are being dynamically allocated and stored.

For example, I have something like:

vector<Enemy*> Enemies; 

and I'll be deriving from the Enemy class and then dynamically allocating memory for the derived class, like this:

enemies.push_back(new Monster()); 

What are things I need to be aware of to avoid memory leaks and other problems?

like image 289
akif Avatar asked Sep 01 '09 07:09

akif


People also ask

How can you prevent memory leak in C using dynamic memory allocation?

The only way to avoid memory leak is to manually free() all the memory allocated by you in the during the lifetime of your code. You can use tools such as valgrind to check for memory leaks. It will show all the memory that are not freed on termination of the program.

Can smart pointers leak memory?

Even when using smart pointers, is it still possible to have memory leak ? Yes, if you are not careful to avoid creating a cycle in your references.

Does dynamic memory allocation leads to memory leak?

Dynamic memory allocation malloc and not deallocating it.This leads to memory leaks. We should always deallocate the memory which is Dynamically allocated otherwise the program will consume memory until it is shut down.

Do vectors dynamically allocate memory?

Arrays have to be deallocated explicitly if defined dynamically whereas vectors are automatically de-allocated from heap memory.


1 Answers

std::vector will manage the memory for you, like always, but this memory will be of pointers, not objects.

What this means is that your classes will be lost in memory once your vector goes out of scope. For example:

#include <vector>  struct base {     virtual ~base() {} };  struct derived : base {};  typedef std::vector<base*> container;  void foo() {     container c;      for (unsigned i = 0; i < 100; ++i)         c.push_back(new derived());  } // leaks here! frees the pointers, doesn't delete them (nor should it)  int main() {     foo(); } 

What you'd need to do is make sure you delete all the objects before the vector goes out of scope:

#include <algorithm> #include <vector>  struct base {     virtual ~base() {} };  struct derived : base {};  typedef std::vector<base*> container;  template <typename T> void delete_pointed_to(T* const ptr) {     delete ptr; }  void foo() {     container c;      for (unsigned i = 0; i < 100; ++i)         c.push_back(new derived());      // free memory     std::for_each(c.begin(), c.end(), delete_pointed_to<base>); }  int main() {     foo(); } 

This is difficult to maintain, though, because we have to remember to perform some action. More importantly, if an exception were to occur in-between the allocation of elements and the deallocation loop, the deallocation loop would never run and you're stuck with the memory leak anyway! This is called exception safety and it's a critical reason why deallocation needs to be done automatically.

Better would be if the pointers deleted themselves. Theses are called smart pointers, and the standard library provides std::unique_ptr and std::shared_ptr.

std::unique_ptr represents a unique (unshared, single-owner) pointer to some resource. This should be your default smart pointer, and overall complete replacement of any raw pointer use.

auto myresource = /*std::*/make_unique<derived>(); // won't leak, frees itself 

std::make_unique is missing from the C++11 standard by oversight, but you can make one yourself. To directly create a unique_ptr (not recommended over make_unique if you can), do this:

std::unique_ptr<derived> myresource(new derived()); 

Unique pointers have move semantics only; they cannot be copied:

auto x = myresource; // error, cannot copy auto y = std::move(myresource); // okay, now myresource is empty 

And this is all we need to use it in a container:

#include <memory> #include <vector>  struct base {     virtual ~base() {} };  struct derived : base {};  typedef std::vector<std::unique_ptr<base>> container;  void foo() {     container c;      for (unsigned i = 0; i < 100; ++i)         c.push_back(make_unique<derived>());  } // all automatically freed here  int main() {     foo(); } 

shared_ptr has reference-counting copy semantics; it allows multiple owners sharing the object. It tracks how many shared_ptrs exist for an object, and when the last one ceases to exist (that count goes to zero), it frees the pointer. Copying simply increases the reference count (and moving transfers ownership at a lower, almost free cost). You make them with std::make_shared (or directly as shown above, but because shared_ptr has to internally make allocations, it's generally more efficient and technically more exception-safe to use make_shared).

#include <memory> #include <vector>  struct base {     virtual ~base() {} };  struct derived : base {};  typedef std::vector<std::shared_ptr<base>> container;  void foo() {     container c;      for (unsigned i = 0; i < 100; ++i)         c.push_back(std::make_shared<derived>());  } // all automatically freed here  int main() {     foo(); } 

Remember, you generally want to use std::unique_ptr as a default because it's more lightweight. Additionally, std::shared_ptr can be constructed out of a std::unique_ptr (but not vice versa), so it's okay to start small.

Alternatively, you could use a container created to store pointers to objects, such as a boost::ptr_container:

#include <boost/ptr_container/ptr_vector.hpp>  struct base {     virtual ~base() {} };  struct derived : base {};  // hold pointers, specially typedef boost::ptr_vector<base> container;  void foo() {     container c;      for (int i = 0; i < 100; ++i)         c.push_back(new Derived());  } // all automatically freed here  int main() {     foo(); } 

While boost::ptr_vector<T> had obvious use in C++03, I can't speak of the relevance now because we can use std::vector<std::unique_ptr<T>> with probably little to no comparable overhead, but this claim should be tested.

Regardless, never explicitly free things in your code. Wrap things up to make sure resource management is dealt with automatically. You should have no raw owning pointers in your code.

As a default in a game, I would probably go with std::vector<std::shared_ptr<T>>. We expect sharing anyway, it's fast enough until profiling says otherwise, it's safe, and it's easy to use.

like image 79
GManNickG Avatar answered Oct 05 '22 00:10

GManNickG