繁体   English   中英

C ++“访问冲突读取位置”错误

[英]C++ “Access violation reading location” Error

我在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这样的偏移量的Access Reading Violation意味着Vertex* f; 在你的getCost函数中接收null,并且当试图访问null顶点指针中的成员adj时(即在f ),它偏移到adj (在这种情况下,72个字节(十进制中的0x48个字节)),它是读取0null存储器地址附近。

执行这样的读取会违反受操作系统保护的内存,更重要的是,无论您指向的是什么都不是有效的指针。 确保findvertex没有返回null,或者在使用它之前对f进行比较以保持自己的理智(或使用断言):

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;

这会导致访问冲突。

暂无
暂无

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

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