因此,我在为char *分配内存时被传递给我的shape类的构造函数时遇到问题,我不断收到错误,提示“malloc:* error 0x01000e0 :被释放的指针未被分配“。我做了大量的谷歌搜索,我找到答案,但他们没有意义,我不明白什么是错的。 shapeName是受保护的char *形状的成员。广场是一个形状的孩子。如果有人能解释什么是错误的,将不胜感激,谢谢。在C++中为char *分配内存时遇到问题
我的构造函数:
Shape::Shape(Point* origin,char* name) {
this->origin = origin;
this->shapeName = (char*) new char(strlen(name)+1);
strcpy(shapeName, name);
}
我的析构函数:
Shape::~Shape() {
delete shapeName;
delete origin;
}
广场的构造函数:
Square::Square(Point* origin, char* squareName, double side)
: Shape(origin, squareName){
side_a = side;
}
我的电话:
Square s(new Point(5,7),"Square - S", 12);
s.display();
cout << "The area of " << s.getName() << " is: " << s.area() << endl;
cout << "The perimeter of " << s.getName() << " is: " << s.perimeter();
我我听说过铸造'malloc',但我从来没有听说过铸造'new'。 – chris 2013-03-23 03:58:10
为什么不使用std :: string?它会自动管理内存。 – 2013-03-23 04:39:29