#include <iostream>
#include <cstring>

using namespace std;

class Cow
{
	char name[20];
	char * hobby;
	double weight;
	public:
		Cow()
		{
			strcpy(name,"peter");
			strcpy(hobby,"nothing");
			weight = 1.0;
		}

		Cow(const char * nm, const char * ho, double wt)
		{
			int len = strlen(ho);
			strncpy(name,nm,19);
			name[19] = '\0';
			hobby = new char[len + 1];
			strcpy(hobby,ho);
			weight = wt;
		}

		Cow(const Cow & c)
		{
			int len = strlen(c.hobby);
			strcpy(name,c.name);
			hobby = new char[len + 1];
			strcpy(hobby,c.hobby);
			weight = c.weight;
		}

		~Cow()
		{
			delete [] hobby;
		}

		Cow & operator=(const Cow & c)
		{
			strcpy(name,c.name);
			delete [] hobby;
			hobby = new char[strlen(c.hobby) + 1];
			strcpy(hobby,c.hobby);
			weight = c.weight;
        }

		void ShowCow() const
		{
			cout << "Name: " << name << endl
				<< "Hobby: " << hobby << endl
				<< "Weight: " << weight << endl;
		}
};

int main()
{
    Cow cow1;
    cow1.ShowCow();

    return 0;
}

Program just crashes, spent time on it, but can't seem to find the problem. Does anyone see the problem?

Recommended Answers

All 6 Replies

Use a debugger (or pepper it with cout statements) to see how far it gets in execution. If you can't find it after that, post back and I'll compile it.

Line 15 uses hobby as the first argument of strcpy without ever having initialized it.

Ohhh, I actually got it myself! I just used the new keyword for hobby above line 15 and it worked. Anyone know why it's necessary to do this? Won't strcpy() copy the address of the first letter of the string to the hobby pointer, making it an array of char (and adding an addition null character since that's what strcpy() does).

Also, does strcpy() overwrite the contents in the destination string, or does it continue to add onto it?

You robbed him of that fun!! Only kidding.

Won't strcpy() copy the address of the first letter of the string to the hobby pointer,

The compiler knows that hobby is a pointer, but there's no space allocated, so it's not pointing to anything.

strcpy won't keep adding on.

Ohh jonsca, I understand. Thank you!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.