【发布时间】:2010-08-15 14:53:30
【问题描述】:
我正在尝试重载赋值运算符以执行多边形对象的深层复制,程序编译但我在最后遇到了一个我想要清除的错误。以下是相关代码,如果您认为我需要添加更多内容,请发表评论。假设正确的 #include's 并且 << 运算符被重载以进行正确的输出等...
错误是:malloc: * 对象 0x1001c0 的错误:未分配指针被释放 * 在 malloc_error_break 中设置断点进行调试。
//Polygon.h
// contains two classes PolygonNode and Polygon
class PolygonNode //Used to link points in a polygon so that they can be iterated through in order
{
public:
...
methods etc
...
private:
Point pt_; // the points in the polygon are made using the Point class
PolygonNode* link_ ; // pointer to the next point in the polygon
};
class Polygon // Connects points and forms a polygon
{
public:
...
Polygon& operator= (Polygon ply);
void Polygon::addPoint(const Point &p);
// methods etc
...
private:
int numPoints_;
bool closed_polygon_;
PolygonNode* first_ ; // points to the first point of the polygon
PolygonNode* last_ ; // points to the last point of the polygon
};
//Polygon.cpp
...
PolygonNode::~PolygonNode()
{
delete link_ ; // possible problem area
}
Polygon::~Polygon()
{
delete first_ ; // possible problem area
last_ = NULL ;
}
void Polygon::addPoint(const Point &p)
{
PolygonNode* ptr ;
ptr = new PolygonNode(p) ;
if( last_ != NULL )
last_->setLink(ptr) ;
last_ = ptr ;
if( first_ == NULL )
first_ = last_ ;
numPoints_++ ;
}
Polygon& Polygon::operator= (const Polygon ply)
{
for (int i = 0; i < ply.numPoints()-1; i++)
{
addPoint(ply.getPoint(i));
}
if (ply.isClosed())
{
closePolygon();
}
else
{
addPoint(ply.getPoint(ply.numPoints()-1));
}
return this;
}
void Polygon::addPoint(const Point &p)
{
PolygonNode ptr ;
ptr = new PolygonNode(p) ;
if( last_ != NULL )
last_->setLink(ptr) ; // sets the last pointer to the new last point
last_ = ptr ;
if( first_ == NULL )
first_ = last_ ;
numPoints_++ ;
}
...
//main.cpp
Polygon ply;
...
Point pt0(0,0);
Point pt1(1,1);
ply.addPoint(pt0);
cout << "ply = " << ply << endl;
Polygon newply;
newply = ply; // use of the assignment operator
cout << "Polygon newply = ply;" << endl;
cout << "newply = " << newply << endl;
cout << "ply = " << ply << endl;
newply.addPoint(pt1);
cout << "newply.addPoint(Point(0,0)); " << endl;
cout << "newply = " << newply << endl;
cout << "ply = " << ply << endl;
...
我在其他地方读到这可能是由于 OS 10.6 或 Xcode 3.2 中的错误,如果有解决方法,有人可以给我详细说明如何解决问题,我对 Xcode 没有太多经验.
已编辑:添加了使用 delete 的部分代码,请注意它正在用于 Polygon 和 PolygonNode 的析构函数中
修改:添加了分配link_的部分代码,setLink是一个简单的setter方法。
【问题讨论】:
-
该错误似乎是在抱怨内存是如何被释放的,但是您目前没有显示任何这样做的代码。任何使用
free或delete的代码都可能与此错误非常相关。 -
@TheUndeadFish:我更新了问题,请参阅底部的编辑
-
你在哪里分配
link_变量?您的示例中缺少该部分代码。 -
@PC2st:我更新了,注意addPoint方法
-
您是否实现了构造函数并将指针初始化为空?错误消息提示一个未初始化的指针。
标签: c++ xcode pointers operator-overloading