C++ "Access violation reading location"错误
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
的偏移量的访问读取冲突意味着您的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;
这会导致访问违规。
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 我在发布模式下运行时收到"Access violation reading location"错误 - C++
- 链接器错误:"cannot move location counter backwards (from 200009f8 to 20000800)"
- 如何修复我的 c++ 毕达哥拉斯三重查找器中的'access violation reading location'错误?
- 矩阵 - "Access violation writing location 0x00900B0C" - C++ 中的错误
- c++:链表错误" Access violation reading location"
- msftedit "Access violation reading location 0x00000008"错误.dll SetWindowSub类中的RichEdit控件
- 指针已初始化,但我有错误"Access violation reading location 0xCCCCCCCC".为什么?
- 从C程序访问C++函数时,收到错误消息"Access violation reading location"
- 为什么装配中会出现"Access violation reading location"错误?
- 如何解决OpenCV中的"Access violation reading location"错误?
- C++ "Access violation reading location"错误
- 矢量存储限制的向量 - 获得"Microsoft C++ exception: std::bad_alloc at memory location 0x0031650C."错误
- "Access violation reading location 0x0000000c"错误