I have a class called Chaine like in the code below :
class Chaine {
unsigned int _size;
char* _data;
public:
Chaine();
~Chaine();
Chaine(const char* str);
unsigned int size() const;
char get(unsigned int i);
};
I've written a function which takes an instance of Chaine and don't do anything (annexe). In my main, when I call annexe(ch1), it gives me an error which says "double free or corruption (fasttop)". the call annexe(ch2) works correctly. If I use the annexe function with a reference to an instance, it works, but i don't understand why.
void annexe(Chaine s) {
}
int main() {
Chaine ch1("Achraf");
Chaine *ch2 = new Chaine("AchrafA");
printf("%d\n", ch1.size());
printf("%d\n", ch2->size());
annexe(ch1);
annexe(*ch2);
delete ch2;
return 0;
}
My constructors and desctructors are the followings :
Chaine::Chaine() {
_size = 0;
_data = NULL;
printf("constructor %s(%d): %s\n", __FILE__,__LINE__,__func__);
}
Chaine::Chaine(const char* str) {
_size = strlen(str);
_data = new char[_size+1];
strcpy(_data, str);
}
Chaine::~Chaine() {
if (_data != NULL) {
delete[] _data;
}
printf("destructor %s(%d): %s\n", __FILE__,__LINE__,__func__);
}