Thursday, November 14, 2019

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

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...