c++ - 我的代码在第二次调用 STL::stack::push() 时出现段错误

标签 c++ stl

在下面的代码中,它使用了 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

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);
}

最佳答案

使用 malloc() 分配对象不会初始化对象。

随后将对象复制到分配的存储空间会导致未定义的行为,因为被复制的对象现在有机会与 malloc() 创建的未初始化 对象进行交互.这可能会以多种方式造成严重破坏,所有这些都取决于所涉及对象的确切细节。

例如,编译器希望销毁被复制过来的对象,但该对象实际上并未初始化。使用移动语义,左侧和右侧的对象可以交互(例如,移动或交换存储),但左侧的对象并不处于一致的状态,因为它从未被初始化。

要更正您的代码,请替换这两行:

  Creature* creaturePoint = (Creature*) malloc(sizeof(Creature));
  *creaturePoint = Creature(x, y, 'r');

用这一行:

  Creature* creaturePoint = new Creature(x, y, 'r');

另外,当你释放这个对象时,一定要使用delete,而不是free()

关于c++ - 我的代码在第二次调用 STL::stack::push() 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20591007/

相关文章:

c++ - 在 Boost::asio 中使用套接字类的成员函数或公共(public)函数?

C++ - 允许通过基类(接口(interface))访问,禁止通过派生类(具体实现)访问?

c++ - 从 vector<> 中删除重复项的最快方法

c++ - 使用 union 作为 std::unordered_map 的键

c++ - 为线程安全写入映射中的队列时互斥

c++ - 使用c++ STL的多维 vector 求解

Python3 + ctypes回调在简单示例中导致内存泄漏

c++ - box2d,接触的哪个夹具是其他夹具?

c++ - C++中的引用代表对象吗?

c++ - 如何打印对的第二部分? EX : pair<int, 对<整数,整数>>