简体   繁体   English

在C ++中的向量中使用指针后出现段错误

[英]Segfault after using pointers in vector in C++

i am running into a segfault in my c++ program and can't figure out my mistake. 我在我的C ++程序中遇到了段错误,无法弄清楚我的错误。
I have a class Map which is a 2D-vector of objects of the class MapCells. 我有一个Map类,它是MapCells类对象的2D向量。 The task is to go from cell to cell. 任务是从一个单元到另一个单元。 From each cell, there are two possible ways to other cells. 从每个单元格到其他单元格有两种可能的方式。 Maybe some 'pseudo' code can explain it better: 也许一些“伪”代码可以更好地解释它:

//map.h

class MapCell {
private:
    MapCell *p_way1_, *p_way2_;
    int some_information_;

public:
    MapCell* getWayPointer1();
    MapCell* getWayPointer2();
    int getInformation();

    void setWayPointer1(MapCell* new_p_way1);
    void setWayPointer1(MapCell* new_p_way2);
};

class Map {
private:
    std::vector< std::vector<MapCell> > map_;
public:
    void initializeMap();
    MapCell* getStartPointer();
};

int main()
{
    Map map;
    map.initializeMap();

    MapCell *p_current_cell, *p_next_cell;
    p_current_cell = map.getStartPointer();

    while(p_current_cell->getInformation() != 0)
    {
        if(p_current_cell->getInformation() == 1)
        {
            p_next_cell = p_current_cell->getWayPointer1();
        }
        else
        {
            p_next_cell = p_current_cell->getWayPointer2();
        }

        p_current_cell = p_next_cell;
    }

    return 0;
}

This is only a little part of the real code. 这只是真实代码的一小部分。 But i think i made a fundamental mistake so i hope this is enough code to fix it. 但是我认为我犯了一个根本性的错误,所以我希望这足以解决它。 The problem is, that my code runs for minutes without problems and suddenly i get a segfault. 问题是,我的代码运行了几分钟没有问题,突然我遇到了段错误。 gdb states, that the segfault happens when getInformation() is called. gdb指出,在调用getInformation()时会发生段错误。 I also found out, that at some point all p_way2_ vectors lead to nonsense. 我还发现,在某些时候所有p_way2_向量都导致废话。 Can you help me? 你能帮助我吗?

Thank you very much in advance! 提前非常感谢您!

Problem in lines 排队问题

MapCell* p_current_cell, p_next_cell;

MapCell* p_way1_, p_way2;

Second parameter is not pointer and MapCell is implicit convert from pointers (or you will get multiple compile-times errors). 第二个参数不是指针,而MapCell是从指针隐式转换的(否则您将获得多个编译时错误)。 Try change to 尝试更改为

MapCell* p_current_cell, *p_next_cell;

MapCell* p_way1_, *p_way2;

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

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