同じクラスのメソッドからクラスのメンバーにアクセスしようとするとセグメンテーションが発生しますが、それはまったく意味がありません。Segfault使用時* this
私は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;
}
...とのLocクラスからCOORDのinheirits ...
class Loc
{
public:
int x, y;
//Constructor
Loc(int xPos, int yPos) : x(xPos), y(yPos) {}
};
segfaultは、コメントによって示されるように、Coord :: getValidMoves()で発生します。そのコードをステップ実行して* thisまたはxまたはthis-> xを監視すると、「0xbaadf00dでメモリにアクセスできない」というメッセージが表示されます
なぜこのようなことが起こりますか?私はどこを台無しにしましたか?メソッドで*これをアクセスしようとするとsegfaultが発生する可能性があります。
オブジェクトがそのメソッドの実行中にオブジェクトを削除していますか(同じスレッド内の別のスレッドまたは別のコールバック)ですか? –
最適化を有効にしていますか? – Omnifarious
補足として、あなたは(Coord test = * this; '、' bool Coord :: operator ==(Coord coord) ')をいくつかの場所に'初期化されていない)ポインタメンバーはコピーctor(またはassigment opまたはdestructor)はありません。 –