I'm struggling with an error related to the copie construction in C++. Here is a code illustrating my question:
//File MYString.h
#ifndef __MYSTRING_H__
#define __MYSTRING_H__
#include <cstring>
#include <iostream>
using namespace std;
class MYString
{
private:
char * m_ptr;
void allocation(int);
int m_lg;
public:
MYString ();
MYString (const char * );
~MYString ();
MYString(const String & );
};
#endif
//File MYString.cpp
#include "MYString.h"
MYString::MYString ()
{
m_ptr= NULL;
m_lg=0;
allocation (1);
m_ptr[0]='\0';
}
void MYString::allocation(int a)
{
delete m_ptr;
m_lg=a;
m_ptr=new char[m_lg];
}
MYString ::MYString (const char * str)
{
m_ptr = NULL;
allocation ( strlen(str)+1 );
strcpy ( m_ptr, str );
}
//copy constructor
MYString::MYString(const MYString & str)
{
allocation(str.m_lg);
strcpy(m_ptr,str.m_ptr);
}
MYString :: ~MYString()
{
delete m_ptr;
}
//File main.cpp
#include <MYString.h"
int main()
{
MYString chaine0("Toto");
MYString chaine1(chaine1); //ERROR free(): invalid size
//Abandon (core dumped)
//However, this works fine
//MYString * chaine0 = new String("Toto");
//MYString *chaine0= new String(chaine0);
return 0;
}
I'm getting an error when I execute the gererated exec : //ERROR free(): invalid size //Abandon (core dumped)
However, when I use the dynamic writing as explained in the main.cpp, this works fine.
Any explanations ?
Thanks