simple_geek simple_geek - 2 months ago 28
C++ Question

Program finished with exit code 10

I am a beginner in C++. I am trying to implement copy constructor.
I hope I had followed the correct syntax of copy constructor.
But whenever I compile my code it'll finish without any errors but at run time it says "Program finished with exit code 10".
I'm working in Clion IDE. When I tried in Mac terminal it showed "Bus error: 10"

I could figure out that copy constructor is causing this problem.
I tried by Commenting it and running the program, it worked fine, when I uncomment it the above problem is caused.

Please help me figure out where I went wrong.

Thank you.

Here is my code:

#include <iostream>

using namespace std;

class Person {
char *name;
int age;
public:
Person ();
Person (char *, int age = 18);
Person (const Person &p);
void output ();
};

Person ::Person() {
name = new char[20]();
age = 0;
}

Person ::Person(char *str, int age) {
name = new char[50]();
strcpy(name, str);
this->age = age;
}

Person ::Person(const Person &p) {
strcpy(name, p.name);
age = p.age;
}

void Person ::output() {
cout << "\nName = " << name;
cout << "\nAge = " << age << endl;
cout <<"-------------------------------------------------------------------------------------------------------------------------\n";
}

int main () {
Person p1;
Person p2("Name");
Person p3 ("Name", 20);
Person p4 = p2;

cout << "\nThe Output of the Object Called by Default Constructor\n\n";
p1.output();
cout << "\nThe Output of the Object Called by Parameterised Constructor with Default Argument\n\n";
p2.output();
cout << "\nThe Output of the Object Called by Parameterised Constructor Overriding Default Argument \n\n";
p3.output();
cout << "\nThe Output of the Object Called by Copy Constructor (Copying p2 Object that is the second output)\n\n";
p4.output();
return 0;
}

Answer

Were is you allocation?
Person ::Person(const Person &p) { strcpy(name, p.name); age = p.age; }
You should allocate memory for your member name the size of strlen(p.name)+1 bytes before copying data to it.

Comments