Reputation: 1215
Would anyone please explain this case: why I am facing 'double free' problem in this simple code?
void Rreceive (myclass){}
int main () {
myclass msg (1);
Rreceive(msg);
return 0;
}
where myclass
is:
class myclass
{
private:
HeaderType header;
byte * text;
public:
myclass(int ID);
~myclass();
HeaderType getHeader();
byte * getText();
};
myclass::myclass(int ID){
header.mID = ID;
text = (byte *)malloc (10);
memset (text, '.', 10);
}
myclass::~myclass(){
free (text);
}
HeaderType myclass::getHeader(){
return header;
}
byte * myclass::getText(){
return text;
}
and HeaderType is:
typedef struct {
int mID;
}HeaderType;
The error is: *** glibc detected *** ./test: double free or corruption (fasttop): 0x0868f008 ***...
Upvotes: 2
Views: 318
Reputation: 4763
When you enter your Rreceive function you call the default copy constrcuctor which will not make a deep copy of your text pointer (in other words, he will just assign the pointer to the new copy).
When exiting the Rreceive scope you free (text) from the copied instance, which will point to the same memory address.
The you will try to free the same memory address again when exiting the scope of your main function.
Upvotes: 5