2013-04-14 189 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