Copy Constructor with an Array Crashing!!!

I know everything works except my copy constructor! There are no errors. The program crashes when it goes to access the copy constructor. Anybody have an clue as to why the copy constructor isn't working?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#include    <cstring>       // access to C str functions
#include    "String.h"      // access String class
using namespace std;

String::String( int size )// default constructor
{
    cout << "String(" << size << ")\n";
    str  = new char[ size ];

    cout << "\tstr at " << hex << ( void * ) str << '\n';
    *str = '\0';
}

String::String( const char *s )//constructor
{
    cout << "String(" << s << ")\n";
    str = new char[ strlen(s) + 1 ];

    cout << "\tstr at " << hex << ( void * ) str << '\n';
    strcpy(str, s);
}

String::String( const String &s)//copy constructor
{
	//s.str
	//str is what seing out or current object
	for(size_t i = 0; i <= strlen(s.str); i++)
	{
		str [i] = s.str[i];
	}
}

String::~String( )//deconstructor
{
	if (*str)
		delete[] str;
}

const String &String::operator =( const String &s ) //operator
{
    for(size_t i = 0; i <= strlen(s.str); i++)
	{
		str [i] = s.str[i];
	}
	return s;
}

ostream &operator <<( ostream &out,	//ostream out rule -- google
                     const String &rhs )  //operator
{
    for(size_t i = 0; i < strlen(rhs.str); i++)
	{
		out << rhs.str[i];
	}
	return out;
}


Hi,

Just wondering if you are going past the end of the array by using the <= operator in the for loop. The normal idiom is:

for (a = 0; a < length; ++a ) {}

Do you have the same problem in the assignment operator?
You don't allocate any memory in your copy constructor, as you do in your other constructors. Why is this?

Your destructor is almost certainly wrong. If it is valid to dereference str, str needs to be deleted.
Topic archived. No new replies allowed.