无法写入使用malloc初始化的位置

-5 c++ malloc

我试图测试我的程序的一部分是否正常工作,但在运行以下代码时,

Car *carList;
carList = (Car*) malloc (length * sizeof(Car));
carList[0].setMake("a");
carList[0].setModel("b");
carList[0].setYear("c");
carList[0].setColor("d");
carList[0].printCar();
Run Code Online (Sandbox Code Playgroud)

该程序在第一个函数调用setMake中遇到问题.这是我的车类:

class Car {
    private:
        string cmake;
        string cmodel;
        string cyear;
        string ccolor;

    public:
        Car(){};
        Car(string *cmake, string *cmodel, string cyear, string *ccolor);
        void printCar(){
            cout << "Make: " << cmake << endl;
            cout << "Model: " << cmodel << endl;
            cout << "Year: " << cyear << endl;
            cout << "Color: " << ccolor << endl << endl;
            return;
        };
        string getMake(){return cmake;};
        string getModel(){return cmodel;};
        string getYear(){return cyear;};
        string getColor(){return ccolor;};

        void setMake(string a){cmake = a;};
        void setModel(string a){cmodel = a;};
        void setYear(string a){cyear = a;};
        void setColor(string a){ccolor = a;};
};
Run Code Online (Sandbox Code Playgroud)

当它试图执行函数setMake时,我得到一个错误

No source available for "libstdc++-6!_ZN9__gnu_cxx9free_list8_M_clearEv()     at 0x6fc59021" 
Run Code Online (Sandbox Code Playgroud)

谁能告诉我我做错了什么?先感谢您.

Mat*_*att 5

您必须使用new而不是malloc因为必须使用构造函数调用初始化C++对象.

在这种特殊情况下,错误是由于未构造的string对象造成的.