Thursday, July 26, 2018

c++ - double free or corruption (runs ok if reorder lines)

Use example in link, but change to use char * and vector:



#include 
using namespace std;

class Test{
char *myArray;


public:
Test(){
myArray = new char[10];
}

~Test(){
delete[] myArray;
}
};



int main(){
vector q; // line 1
Test t; // line 2
q.push_back(t);
}


It will cause double free or corruption error. However, if run line 2 before line 1, like:




Test t;
vector q;


Then it runs ok. Why is that?



Tested on Xubuntu 12.04 g++ 4.6.3.



Updated:




It's not duplicate question. I understand a copy constructor and an assignment operator are needed (it's already answered in the above link where the sample code is from). However, using int * or queue like that in the original link, but swapping line 1 and line 2, there is still error. Only using char *, and vector and swapping line 1 and line 2 will not cause error. My question is why is this particular case? Can anyone check it in your platform?

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...