C++ "Access violation reading location"错误

C++ "Access violation reading location" Error

本文关键字:location 错误 reading violation Access C++      更新时间:2023-10-16

我在Graph类中有以下Vertex结构:

struct Vertex
{
    string country;
    string city;
    double lon;
    double lat;
    vector<edge> *adj;
    Vertex(string country, string city, double lon, double lat)
    {
        this->country = country;
        this->city = city;
        this->lon = lon;
        this->lat = lat;
        this->adj = new vector<edge>();
    }
};

当调用我编写的名为getCost()的方法时,我一直得到相同的Unhandled Exception

访问违规读取位置0x00000048

我不知道为什么。

getCost()方法:

void Graph::getCost(string from, string to)
{
    Vertex *f = (findvertex(from));
    vector<edge> *v = f->adj;     // Here is where it gives the error
    vector<edge>::iterator itr = v->begin();
    for (; itr != v->end(); itr++)
    {
        if (((*itr).dest)->city == to)
            cout << "nCost:-" << (*itr).cost;
    }
}

方法findvertex()返回类型为Vertex*的值。为什么我一直收到这个错误?

findVertex方法:

Vertex* Graph::findvertex(string s)
{
    vmap::iterator itr = map1.begin();
    while (itr != map1.end())
    {
        if (itr->first == s){
            return itr->second;
        }
        itr++;
    }
    return NULL;
}

其中定义map1

typedef map< string, Vertex *, less<string> > vmap;
vmap map1;

您还没有发布findvertex方法,但具有类似0x00000048的偏移量的访问读取冲突意味着您的getCost函数中的Vertex* f;接收到null,并且当尝试访问null顶点指针中的成员adj(即在f中(时,它偏移到adj(在这种情况下,为72字节(十进制0x48字节((,它在CCD_ 15或CCD_。

这样读取会违反操作系统保护的内存,更重要的是,这意味着你指向的任何指针都不是有效的指针。确保findvertex没有返回null,或者在使用f之前对null进行比较以保持理智(或使用断言(:

assert( f != null ); // A good sanity check

编辑:

如果你有一个map来做类似于查找的事情,你可以使用地图的find方法来确保顶点存在:

Vertex* Graph::findvertex(string s)
{
    vmap::iterator itr = map1.find( s );
    if ( itr == map1.end() )
    {
        return NULL;
    }
    return itr->second;
}

只要确保您仍然小心处理它确实返回NULL的错误情况。否则,您将继续受到此访问侵犯。

Vertex *f=(findvertex(from));
if(!f) {
    cerr << "vertex not found" << endl;
    exit(1) // or return;
}

因为如果findVertex找不到顶点,它可以返回NULL

否则,此f->adj;正在尝试进行

NULL->adj;

这会导致访问违规。

相关文章: