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

Can't write to location initialized with 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();

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

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;};
};

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

No source available for "libstdc++-6!_ZN9__gnu_cxx9free_list8_M_clearEv()     at 0x6fc59021" 

谁能告诉我我做错了什么?提前谢谢你。

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

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

malloc 只是分配内存,它不会初始化 C++ 对象。看起来你想要一个动态大小的 Car 集合,所以 std::vector<Car> 对你来说会更好:

std::vector<Car> carList (length);
carList[0].setMake("a"); //assuming length>0
carList[0].setModel("b");
carList[0].setYear("c");
carList[0].setColor("d");
carList[0].printCar();

这将创建一个 length 大小的 std::vector 默认初始化 Cars,然后在向量中的第一个对象上设置请求的属性并打印它。