3

I'm trying to create a vector of structs which each have a an array of pointers. However, I can't seem to delete the vector without a memory problem.

When I run valgrind

==29801== Invalid free() / delete / delete[] / realloc() ==29801== at 0x4A05A36: operator delete (vg_replace_malloc.c:515) ==29801== by 0x4009D4: test_struct::~test_struct() (in /home/hltcoe/rcotterell/code-switching/a.out) ==29801== by 0x40142B: void std::_Destroy(test_struct*) (in /home/hltcoe/rcotterell/code-switching/a.out) ==29801== by 0x401299: void std::_Destroy_aux::__destroy(test_struct*, test_struct*) (in /home/hltcoe/rcotterell/code-switching/a.out)

EDIT

#include <vector>
using namespace std;

struct test_struct {
  public:
    int * array;
    test_struct() {
       array = NULL;
    }
    ~test_struct() {
       delete[] array;
    } 
   private:
     test_struct(const test_struct& that);
     test_struct& operator=(const test_struct& that);
};

int main(int argc, char ** argv) {

  vector <test_struct> data;

  for (int i = 0; i < 5; ++i) {
       test_struct tmp;
       tmp.array = new int[5];
       data.push_back(tmp);
   }
}

And it gives the following compile error. Any ideas?

billz
  • 44,644
  • 9
  • 83
  • 100
  • possible duplicate of [What is The Rule of Three?](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three) – juanchopanza Jun 04 '13 at 07:13

2 Answers2

3

You should follow rule of three or Use STL container where ever possible:

struct test_struct 
{
  explicit test_struct(int size) : array(size) { }    
  std::vector<int> array;
};


int main()
{
  vector <test_struct> data(5, test_struct(5));

  return 0;
}
Community
  • 1
  • 1
billz
  • 44,644
  • 9
  • 83
  • 100
2

Your solution doesn't work because of test_struct destructor and the fact you're trying to store your structs in a vector.
When test_struct tmp is pushed to the vector, a copy of test_struct is created. Then tmp is destroyed with calling delete[] array and the copy in vector <test_struct> data ends up with a dangling pointer.
You probably need to rethink your architecture, or at least add a copy constructor for the test_struct that will copy the whole array

spiritwolfform
  • 2,263
  • 15
  • 16