析构函数/释放内存的问题

时间:2017-03-26 11:25:13

标签: c++ class memory destructor

所以我对c ++很新,我正在尝试一些基本的动态内存分配,我已经遇到了一些问题。我不确定我做错了什么,但我不能运行以下代码:

班级声明:

class Car {
    double maxSpeed;
    bool isNew;
    char* manufacturerName;

public:
    Car(double = 0, bool = true, char* = "Unknown");
    ~Car();
    Car& operator=(const Car&);


};

构造函数实现:

Car::Car(double maxSpeed, bool isNew, char* manufacturerName) {
    this->maxSpeed = maxSpeed;
    this->isNew = isNew;
    this->manufacturerName = new char[strlen(manufacturerName)];
    strcpy(this->manufacturerName, manufacturerName);
}

析构函数实现:

Car::~Car() {
    delete [] manufacturerName;
}

主要:

int main() {

    Car C(250.0, true, "Name1");
    Car C1(180.0, false, "Name2");
    Car C2;    
    cout << C << C1 << C2;

    return 0;
}

我收到错误消息:

error i get

1 个答案:

答案 0 :(得分:5)

您必须在构造函数中为字符串分配strlen(...)+ 1个字节,以便为结束零字节进行acommodate。您正在写入比当前分配的更多的1个字节。