C++ 我的代码在第二次调用STL::stack::push()时出错
在下面的代码中,它使用ncurses,因此没有printf,我得到一个有趣的segfaultC++ 我的代码在第二次调用STL::stack::push()时出错,c++,stl,C++,Stl,在下面的代码中,它使用ncurses,因此没有printf,我得到一个有趣的segfault // 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 != NU
// 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++;
}
}
在第二次推送时,我的代码segfaults,我知道这一点,因为我交换了它下面的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()
分配对象不会初始化该对象
随后在分配的存储上复制对象会导致未定义的行为,因为被复制的对象现在有机会与malloc()
创建的未初始化对象交互。这可能以各种方式造成严重破坏,所有这些都取决于所涉及对象的确切细节
例如,编译器希望销毁被复制的对象,但该对象实际上没有初始化。使用移动语义,左侧和右侧的对象可以交互(例如,移动或交换存储),但是左侧的对象没有处于一致的状态,因为它从未初始化
要更正代码,请替换以下两行:
Creature* creaturePoint = (Creature*) malloc(sizeof(Creature));
*creaturePoint = Creature(x, y, 'r');
用这一行:
Creature* creaturePoint = new Creature(x, y, 'r');
另外,当您解除分配此对象时,请确保使用
delete
,而不是free()
为什么不通过调试器运行它并查看回溯显示的内容?使用malloc
然后分配到内存位置,就像您在addbioter
函数中所做的那样,不是创建非平凡类型对象的有效方法。为什么不直接使用new
?或者更好的是,首先不要使用指针。除非您需要运行时多态性,否则您应该使用智能指针。我相信@BenjaminLindley突出显示的内容实际上是导致崩溃的原因。尝试用malloc
替换该行,并用creaturePoint=新生物(x,y,'r')替换其后面的行
另外,当你要摆脱它时,一定要删除它,而不是释放它。你不能对这样的对象进行malloc。你必须使用新的操作符。我还怀疑segfault是代码中最小的问题。你需要了解RAII和五法则,并将其牢记在心。@JoeZ成功了,如果你将其作为答案提交,我可以接受!谢谢顺便说一句,为什么马洛克不在这里工作?嗯。。。我想知道是谁投了反对票?我很高兴听到你的关心。
Creature* creaturePoint = new Creature(x, y, 'r');