程序结束,退出码为10

Program finished with exit code 10

本文关键字:退出 结束 程序      更新时间:2023-10-16

我是一个c++初学者。我试图实现复制构造函数。我希望我遵循了复制构造函数的正确语法。但是每当我编译我的代码时,它会没有任何错误地完成,但在运行时它会说"程序结束,退出码为10"。我在clionide中工作。当我在Mac终端上尝试时,它显示"Bus error: 10"

我可以找出是复制构造函数导致了这个问题。我试着注释它并运行程序,它工作得很好,当我取消注释时,导致了上面的问题。

请帮我找出我错在哪里。

谢谢。下面是我的代码:

    #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 Constructornn";
    p1.output();
    cout << "nThe Output of the Object Called by Parameterised Constructor with Default Argumentnn";
    p2.output();
    cout << "nThe Output of the Object Called by Parameterised Constructor Overriding Default Argument nn";
    p3.output();
    cout << "nThe Output of the Object Called by Copy Constructor (Copying p2 Object that is the second output)nn";
    p4.output();
    return 0;
}

如果我只从你的问题的标题回答你的问题,答案将非常简单。

但是首先请阅读如何创建一个最小的,可重复的例如,因为它可以帮助其他人理解检查你的代码。

exit()是终止内置函数,用于正常终止程序。

,它接受一个参数Status code。也表示两种简单状态

  1. 0或EXIT_SUCCESS(宏)表示成功exit(0)exit(EXIT_SUCCESS)
  2. 如果是EXIT_FAILURE,表示失败exit(1)exit(EXIT_FAILURE)

所以对于exit(10)exit(1)的任何其他值,它表示错误。

要了解有关exit()的更多信息,请参阅此处:

  • exit() - cpluscplus
  • exit() vs _Exit()在C和c++ - GeaksforGeaks
  • exit(), abort()和assert() - GeaksforGeaks

现在从你的代码中显示,你是新的 pointers ,所以它会很好地为你读这篇文章,因为它会给吗指导如何以正确的方式使用指针以防止out of memorymemory leaksSegfault错误。

c++核心指南:资源管理规则

分配
Person ::Person(const Person &p) { strcpy(name, p.name); age = p.age; }
在向成员name复制数据之前,应该为其分配strlen(p.name)+1字节大小的内存