0

I'm confused as to how deallocating vector memory works. For the example below,

vector<Object*> vec;

for(int i = 0; i < 10; i++){
  Object* obj = new Object();
  vec.push_pack(obj);
}

//DEALLOCATE CODE HERE//

What should I do to deallocate vec properly? The program seems to run fine as it is but I'm not sure.

melpomene
  • 84,125
  • 8
  • 85
  • 148
Eric Shong
  • 9
  • 2
  • 3
  • 2
    Everything you `new` you have to `delete` - the `vector` doesn't change anything about it – UnholySheep Apr 07 '19 at 21:28
  • 2
    The preferred way is to not allocate dynamically at all, a `vector` is the correct choice in many scenarios – UnholySheep Apr 07 '19 at 21:30
  • just do not use new, use std::unique_ptr instead: – skeller Apr 07 '19 at 21:30
  • Possible duplicate of ["Right" way to deallocate an std::vector object](https://stackoverflow.com/questions/3054567/right-way-to-deallocate-an-stdvector-object) – Talha Apr 07 '19 at 21:32
  • just iterate on the vector to delete each element, then clear (like `resize(0)`) it, see my answer – bruno Apr 07 '19 at 21:36

2 Answers2

1

avoid using new/delete :

std::vector<std::unique_ptr<Object>> vec;

for(int i = 0; i < 10; i++)
{
  vec.push_pack(std::make_unique<Object>());
}

the unique_ptr will take care of deletion

skeller
  • 1,151
  • 6
  • 6
0

how deallocating

for instance do

for(auto o : vect){
  delete o;
}
vect.clear();

Note you written push_pack rather than push_back to fill the vector


making a full program :

#include <vector>
using namespace std;

class Object{};

int main()
{
  vector<Object*> vec;

  for(int i = 0; i < 10; i++){
    Object* obj = new Object();
    vec.push_back(obj);
  }
  for(auto o : vec){
    delete o;
  }
  vec.clear();
}

Compilation and execution under valgrind :

pi@raspberrypi:/tmp $ g++ v.cc
pi@raspberrypi:/tmp $ valgrind ./a.out
==9157== Memcheck, a memory error detector
==9157== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==9157== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==9157== Command: ./a.out
==9157== 
==9157== 
==9157== HEAP SUMMARY:
==9157==     in use at exit: 0 bytes in 0 blocks
==9157==   total heap usage: 16 allocs, 16 frees, 20,358 bytes allocated
==9157== 
==9157== All heap blocks were freed -- no leaks are possible
==9157== 
==9157== For counts of detected and suppressed errors, rerun with: -v
==9157== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 3)

all allocated memory was freed

bruno
  • 32,421
  • 7
  • 25
  • 37