繁体   English   中英

无效写入 valgrind 导致分段错误

[英]invalid writes valgrind causing segmentation fault

我正在尝试创建一个迷宫 class ,它可以读取具有迷宫描述的输入 stream 并返回迷宫。 但是,当我使用这个给定的输入 stream 运行测试时:

20 10
####################
#................<.#
#..................#
#...###............#
#.....#............#
#.....#............#
#...###............#
#..................#
#..................#
####################

它给出了分段错误,我在 valgrind 上运行 object 文件以检查发生了什么:

Invalid write of size 8
==2482545==    at 0x4032CD: Maze::setTile(Position const&, Tile*) (maze.cpp:47)
==2482545==    by 0x40347B: Maze::read(std::istream&) (maze.cpp:67)
.....
==2482545==  Address 0x0 is not stack'd, malloc'd or (recently) free'd

我真的不明白为什么会出现分段错误或无效写入,在我的代码中,我应该为我的 setTile function 中的每个图块分配空间,所以应该有空间给我写。 我还将 tile_collection 与构造函数堆叠在一起,因此当我调用 Maze(20,10) 时应该初始化 tile_collection,并且 setTile 内部的调整大小应该可以正常工作。 你能指出我错过了什么吗? 先感谢您。 I know that I asked a really similar question 3 hours ago but I am still stuck on this invalid write.(The Position class and tilefactory class are 2 given files so they should work fine) This is the class declared in header file:


class Maze {
private:
  // TODO: add fields
  int Width;
  int Height;
  std::vector<Tile*> tile_collection;

这是我的 cpp 文件:

Maze::Maze(int width,int height):
  Width(width),Height(height){
  tile_collection[(width-1)*(height)];
}

}


void Maze::setTile(const Position &pos,Tile *tile){
  tile_collection[pos.getX()+pos.getY()*(Width)]=tile;
}


Maze *Maze::read(std::istream &in){
  int x;int y;char c;
  if ((in>>x)&&(in>>y)){
      Maze *new_maze=new Maze(x,y);
      //loop over the specified maze dimension
        for (int i=0;i<y;i++){
          for (int j=0;j<x;j++){
            if (in>>c){
              //using tilefactory to change character into a tile
              TileFactory *fac=TileFactory::getInstance();
              Tile* temp=fac->createFromChar(c);
              //if createFromChar fails, return nullptr, otherwise set tile at position j,i
              if (temp==nullptr){
                return nullptr;
              }
              else{
                new_maze->setTile(Position(j,i),temp);
              }
            }
          }
        }
        return new_maze;
  }
  else{
    return nullptr;
  }
}

我怀疑你看到的错误是这条线的结果:

          TileFactory *fac=fac->getInstance();

您正在声明一个名为fac的本地指针变量,但您试图通过相同的指针变量调用方法( getInstance() ),甚至在它被设置为任何东西之前。 对我来说似乎是灾难的秘诀!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM