0

I have a problem using the data base "map". I am writting a progrem that implement BFS (breadth first search) at graphs. In oreder to keep the "key" (string) and the "value" (Vertex- a class I created) I use :
map<string, Vertex*> graph

"graph" is a field at class "Graph" that include some functions. One of the functions is " void addv(string& key)" - her goal is to add a new Vertex to the map. here a copy of the function:

void Graph::addv(string& key) // add vertex to the graph
{

// initilazited the map by values
  string tempKey = key;
  Vertex v(tempKey);
  v.initialize(tempKey); // at the begining, the color of all vertexes is 
  //"white".
  Vertex * p =&v;
  graph.insert(pair<string,Vertex*>(tempKey, &v));  

}

From the the main program I run this program:

int main()
{
  Graph g;
  string v1, v2, e1,e2 ,name;
  cout << "enter vertexes" << endl;
  cin >> v1;
  cin >> v2;
  g.addv(v1); g.addv(v2);
}

My problem is the "return values" of the function. At the running the program my input value were: v1= 'A', v2= 'B'. When I debug the program I noticed that when the process get to mention fuction, the value of the "graph" nearly to exit from the function were as you can see at the picture below:

before

But at final step of the process at the fuction, the values change as you can see at this picture:

after

As you can see the "key" value at parmeter "second" change to " " instead of "A".

Thank you for your help.

James Adkison
  • 9,412
  • 2
  • 29
  • 43
DBM
  • 71
  • 7

2 Answers2

0

You're inserting a pointer to a variable with local storage duration. It is the nature of such variables to get cleaned up again when the function is exited and you end with a dangling pointer.

To solve the issue, either copy the struct into the map (std::map<std::string, Vertex>, note the dropped astrisk!) or create the values on heap (Vertex* v = new Vertex(tempKey);).

Aconcagua
  • 24,880
  • 4
  • 34
  • 59
0

I think one issue is that as soon as any addv call terminates, the Vertex that was allocated (on the stack) is destroyed, and its memory deallocated. You'd probably want to allocate it on the heap instead (using new for example, but nowadays "using new" should be replaced by `using (the right kind of) smart pointer, in that case, probably a std::unique_ptr that you create with std::make_unique.

Olivier Sohn
  • 1,292
  • 8
  • 18