-3

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__);
}
  • It seems likely that `annexe` takes a `Chaine` by value and you have no copy constructor. Either way, edit your question to include a [mcve]. There is no reason we should sit here and guess what code you didn't include. – Sid S Jan 06 '19 at 02:46
  • If possible, use `std::string` instead and avoid problem like that and simplify your code. – Phil1970 Jan 06 '19 at 03:23

1 Answers1

3
  1. Your function annexe takes a Chaine as a parameter, which will be copied when called (you didn't declare the parameter as a reference).
  2. You did not define a Copy Constructor for the class Chaine, so the default will be used. It does a basic bitwise copy of all data, including the pointer *_data inside your Chaine.
  3. When the function ends, the copy is destroyed, and the respective data behind (the copy of) *data is released, in your destructor.
  4. Later you release the 'original' of *_data, which is a double delete.
Aganju
  • 6,295
  • 1
  • 12
  • 23