Wednesday, 14 March 2018

C++ vector of structs with pointers

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 
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 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?

No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...