【发布时间】:2011-01-22 00:05:07
【问题描述】:
当我尝试从同一个类的方法中访问一个类的成员时,我遇到了段错误,这对我来说根本没有意义。
我有 Tree 类:
class Tree
{
public:
Coord* root;
Tree(int x, int y)
{
root = new Coord(x, y);
populateTree();
}
void populateTree()
{
queue<Coord*> nodes;
nodes.push(root);
while (nodes.size() > 0)
{
Coord* currnode = nodes.front();
nodes.pop();
if ( !(currnode->getValidMoves()) )
{
return;
}
else
{
for (int i = 0; i < MAX_CHILDREN_PER_COORD; i++)
{
if (currnode->children[i] != NULL)
{
nodes.push(currnode->children[i]);
}
}
}
}
}
...和 Coord 类...
class Coord : public Loc
{
public:
Coord(int xPos, int yPos);
Coord* children[MAX_CHILDREN_PER_COORD];
bool getValidMoves();
bool operator==(Coord coord);
bool operator==(Loc loc);
};
Coord::Coord(int xPos, int yPos) : Loc(xPos, yPos) {}
bool Coord::getValidMoves()
{
//This line segfaults
Coord test = *this;
//Global boolean method. Checks found
if (!foundTrue())
{
for (int i = 0; i < MAX_CHILDREN_PER_COORD; i++)
{
//If the above segfaulting line is commented out, this is the first place that segfaults
int newX = x + knightPositions[i].x;
int newY = y + knightPositions[i].y;
if ( !(newX > GRID_X || newX < 0 || newY > GRID_Y || newY < 0) )
{
//knightPositions is a Loc array of length MAX_CHILDREN_PER_COORD
children[i] = new Coord(x + knightPositions[i].x, y + knightPositions[i].y);
//Global 2d array of ints. Gets checked by foundTrue()
found[x + knightPositions[i].x][y + knightPositions[i].y] = true;
}
}
return true;
}
else
{
return false;
}
//Otherwise, just leave it as a blank array
}
bool Coord::operator==(Coord coord)
{
return coord.x == x && coord.y == y;
}
bool Coord::operator==(Loc loc)
{
return loc.x == x && loc.y == y;
}
... 以及 Coord 继承的 Loc 类...
class Loc
{
public:
int x, y;
//Constructor
Loc(int xPos, int yPos) : x(xPos), y(yPos) {}
};
如 cmets 所示,段错误发生在 Coord::getValidMoves() 中。如果单步执行代码到该点,然后监视 *this 或 x 或 this->x,我会得到“无法在 0xbaadf00d 访问内存”
为什么会这样?我哪里搞砸了?我只是不明白如何尝试在方法中访问 *this 可能会导致段错误。
【问题讨论】:
-
当您的对象正在执行其方法之一时,是否有其他东西(另一个线程或同一线程中的古怪回调)删除您的对象?
-
你开启优化了吗?
-
附带说明,您正在为具有(未初始化的)指针成员但没有复制 ctor 的类在多个位置(
Coord test = *this;、bool Coord::operator==(Coord coord))复制Coord(或赋值操作或析构函数)。 -
@Eugen:是的,这是一个旧编程竞赛的练习题,所以我根本不关心良好的编程练习。只要它吐出正确的答案:D
标签: c++ debugging segmentation-fault