[英]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個字節)),它是讀取0
或null
存儲器地址附近。
執行這樣的讀取會違反受操作系統保護的內存,更重要的是,無論您指向的是什么都不是有效的指針。 確保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.