When I compile with Xcode and run this, I get the error, at least 100 times in a row, malloc: *** error for object 0x100180: double free
, with the debugger pointing to line C
. Strangely, In the code I distilled this from, the exact same error occurs, but the debugger points to the equivalent of line B
. I tried but couldn't reproduce that.
If I remove line A
, the code works but I get a major memory leak that crashes the program in about 1 minute. Removing line C
solves the issue but isn't a valid solution because then a_class
doesn't have a proper destructor.
#include <iostream>
#include <vector>
struct a_struct
{
int* dynamic_array;
a_struct(int length) {dynamic_array = new int [length];}
a_struct() : dynamic_array(NULL) {}
~a_struct() { if (dynamic_array != NULL) {delete [] dynamic_array;} } //Line A
};
class a_class
{
public:
a_struct* the_structs;
a_class() {Init();}
a_class(a_class const & origin) {Init();}
void Init(){
the_structs = new a_struct [10]; //Line B
for(int q=0; q<10; q++)
the_structs[q] = a_struct(7);}
~a_class() { if (the_structs != NULL) {delete [] the_structs;} } //Line C
};
int main ()
{
std::vector <a_class> the_objects;
for(int q=0; q<10; q++)
the_objects.push_back(a_class());
while(1)
for(int q=0; q <10; q++)
for(int w=0; w <10; w++)
the_objects[q].the_structs[w] = a_struct(7);
}