在下面的代码中,使用ncurses,所以没有printf,我得到一个有趣的段错误
// Returns the path constructed from A*
void Creature::returnPath(struct Tile* currentTile){
// Declarations
int DEBUG = 0;
int stepX;
int stepY;
int combo;
while(currentTile->parent != NULL){
mvprintw(12 + DEBUG ,0, "in while %i", currentTile->parent);
refresh();
stepX = currentTile->x;
stepY = currentTile->y;
// The path data structure consists of a int split so xxxyyy
combo = (stepX * 1000) + stepY;
mvprintw(12 + DEBUG, 20, "HERE %i %i", &path, &(this->path));
refresh();
path.push(combo);
currentTile = currentTile->parent;
DEBUG++;
}
}
在第二次推送时,我的代码段错误,我知道这是因为我已经在它下面交换了mvprintw()和refresh()并且没有输出
为什么它会在第二次调用时出现段错误?
路径堆栈是下面列出的对象的成员
class Creature{
public:
// The constructor that takes (x,y) as well as a char representation
// of the creature to be blitted
Creature(int x, int y, char blit);
// Draws the creature on the screen at its current position
int drawCreature(WINDOW* window);
// Takes one step
int step(Map* map);
int move(int x, int y, Map* map);
void returnPath(struct Tile* currentTile);
std::stack<int> path;
int x;
int y;
private:
char blit;
};
该生物在这里是malloc'd
int Map::addCreature(int x, int y, char type){
// TODO: have a creature free command
Creature* creaturePoint = (Creature*) malloc(sizeof(Creature));
*creaturePoint = Creature(x, y, 'r');
creatureList[y][x].push_front(creaturePoint);
}
答案 0 :(得分:2)
使用malloc()
分配对象不会初始化对象。
随后在分配的存储上复制对象会导致未定义的行为,因为正在复制的对象现在有机会与malloc()
创建的未初始化的对象进行交互。这可能会以各种方式造成严重破坏,所有这些都取决于所涉及对象的确切细节。
例如,编译器期望破坏正在复制的对象,但该对象实际上并未初始化。使用移动语义,左侧和右侧对象可以交互(例如,移动或交换存储),但左侧的对象不处于一致状态,因为它从未初始化。
要更正您的代码,请替换以下两行:
Creature* creaturePoint = (Creature*) malloc(sizeof(Creature));
*creaturePoint = Creature(x, y, 'r');
这一行:
Creature* creaturePoint = new Creature(x, y, 'r');
此外,当您取消分配此对象时,请务必使用delete
,而不是free()
。