같은 클래스의 메서드 내에서 클래스 멤버에 액세스하려고하면 segfault가 발생합니다.이 클래스는 전혀 의미가 없습니다.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]);
}
}
}
}
}
... 그리고 좌표 운전 클래스 ...
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 데이 클래스를하는 좌표 운전의 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)')에 대해'Coord'의 복사본을 만들고 있습니다. 초기화되지 않은) 포인터 멤버는 있지만 ctor (또는 assigment op 또는 destructor)는 없습니다. –