I have the following Vertex
struct in a Graph
class:
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>();
}
};
When calling the method I've written called getCost()
, I keep getting the same Unhandled Exception
Access violation reading location 0x00000048
and I cannot figure out why.
the getCost()
method:
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;
}
}
The method findvertex()
returns a value of type Vertex*
. Why do I keep receiving this error?
the findVertex method:
Vertex* Graph::findvertex(string s)
{
vmap::iterator itr = map1.begin();
while (itr != map1.end())
{
if (itr->first == s){
return itr->second;
}
itr++;
}
return NULL;
}
Where map1
is defined:
typedef map< string, Vertex *, less<string> > vmap;
vmap map1;
You haven't posted the findvertex
method, but Access Reading Violation with an offset like 0x00000048
means that the Vertex* f;
in your getCost function is receiving null, and when trying to access the member adj
in the null
Vertex pointer (that is, in f
), it is offsetting to adj
(in this case, 72 bytes ( 0x48 bytes in decimal )), it's reading near the 0
or null
memory address.
Doing a read like this violates Operating-System protected memory, and more importantly means whatever you're pointing at isn't a valid pointer. Make sure findvertex
isn't returning null, or do a comparisong for null on f
before using it to keep yourself sane (or use an assert):
assert( f != null ); // A good sanity check
EDIT:
If you have a map
for doing something like a find, you can just use the map's find
method to make sure the vertex exists:
Vertex* Graph::findvertex(string s)
{
vmap::iterator itr = map1.find( s );
if ( itr == map1.end() )
{
return NULL;
}
return itr->second;
}
Just make sure you're still careful to handle the error case where it does return NULL
. Otherwise, you'll keep getting this access violation.
Vertex *f=(findvertex(from));
if(!f) {
cerr << "vertex not found" << endl;
exit(1) // or return;
}
Because findVertex
can return NULL
if it can't find the vertex.
Otherwise this f->adj;
is trying to do
NULL->adj;
Which causes access violation.
User contributions licensed under CC BY-SA 3.0