2013-04-14 46 views
2

我有一个Graph类以下Vertex结构:C++“访问冲突读取位置”错误

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()的方法,我不断收到同样的未处理的异常

访问冲突读取位置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; 
+1

您已将所有内容贴在最相关的部分旁边。提示:findvertex – SomeWittyUsername

+0

你可以发布findVertex吗? – Alan

+0

什么是findvertex?即如果它不返回具体的顶点对象,那就是你的错误。 – Chris

回答

7

您还没有贴findvertex方法,但使用读冲突与像0x00000048偏移意味着你的getCost功能Vertex* f;正在接收空,并试图访问该成员adjnull顶点指针时(即,在f),它抵消到adj(在这种情况下,72字节(十进制的0x48字节)),它的读数接近0null存储器地址。

做这样的读取违反了操作系统保护的内存,更重要的是,无论您指向什么都不是有效的指针。确保findvertex没有返回null,或者做一个空的comparisong使用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。否则,您将不断收到此访问冲突。

+0

我已经相应地替换了findvertex方法,但是,错误仍然是一样的 –

+0

@AlexAlex这意味着即使它发现了某些东西,您可能有两个潜在的问题。一个是你实际上将null插入到特定String键的映射中。另一个是顶点实际上并不在地图中。调试器断点(对于IDE)或者执行键/值的打印并在向地图添加值时执行打印以确保不添加空值将是明智的。 – 2013-04-14 02:35:48

+0

我很感激帮助。我去了,并创建了一个视图方法来打印出地图中的所有顶点。他们都与他们的属性打印,我没有看到任何空值 –

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

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

否则这个f->adj;试图做

NULL->adj; 

这会导致访问冲突。

+0

确实发现了错误,谢谢。但是,如果值真的位于map1中,您是否会看到为什么findvertex方法返回NULL的任何原因?我在别处调用了findvertex方法,并打印出返回顶点的属性就好了。 –

+0

@AlexAlex你的代码没有任何明显的错误。问题不在于查找算法。我认为这是插入到地图中。如果您可以使用一些调试器并在查找算法中放置一个断点来查看map1包含的内容,那么您可以在大约10分钟内解决这个问题。 :) – 2013-04-14 02:30:22