I am very curious why the copy constructor is so important for dynamically highlighting my own specific class.
I am implementing a low-level c-string class with dynamic allocations, and here is a brief overview of my class
class String
{
private:
char * buf;
bool inBounds( int i )
{
return i >= 0 && i < strlen(buf);
}
static int strlen(const char *src)
{
int count = 0;
while (*(src+count))
++count;
return count;
}
static char *strcpy(char *dest, const char *src)
{
char *p = dest;
while( (*p++ = *src++));
return dest;
}
static char* strdup(const char *src)
{
char * res = new_char_array(strlen(src)+1);
strcpy(res,src);
return res;
}
static char * new_char_array(int n_bytes)
{
return new char[n_bytes];
}
static void delete_char_array( char* p)
{
delete[] p;
}
public:
String( const char * s = "")
{
buf = strdup(s);
}
String( String & s)
{
buf = strdup(s.buf);
}
void reverse()
{
}
void print( ostream & out )
{
out << buf;
}
~String()
{
delete_char_array(buf);
}
};
ostream & operator << ( ostream & out, String str )
{
str.print(out);
return out;
}
I know that part of the strdup () function is not entirely correct, but I'm just doing a few tests.
My problem is that I don't have a copy constructor, and my main () is
int main()
{
String b("abc");
String a(b);
cout << b << endl;
return 0;
}
The compiler will tell me double free or corruption (fasttop), and I will find the answers to this question and look at the rules of the Big Three.
Can you guys tell me why my code works without any errors if I have a copy constructor and what does the double release or corruption error (fasttop) mean?