0

The behavior of the code below surprises me:

map<string,long>* map_ptr;
if(true){
    map<string, long> my_map;
    my_map["a"] = 1;
    my_map["b"] = 2;
    my_map["c"] = 3;
    map_ptr = &my_map;
}

//works ONLY IF this for loop comes before the next for loop
for(map<string, long>::iterator itr = map_ptr->begin(); itr != map_ptr->end(); ++itr)
    cout << itr->second << endl; 

// does not work prints random bits
for(map<string, long>::iterator itr = map_ptr->begin(); itr != map_ptr->end(); ++itr)
    cout << itr->first << endl; 

I knew variables created within if statement only have scope within it, but I thought declaring a pointer to them will work. I have limited knowledge about the stack structure of this code, but I thought the variables, though out of scope, are still on the stack so they still exist. But it seems there's more happening than I know of. What surprised me the most is why the first for loop prints out things correctly, but only if it is executed before the second for loop. I guess it has something to do with the type because long is built-in where as string is not, but this is far from sufficing to explain to what's going on.

Please help me understand this code. Thanks!

user1861088
  • 1,683
  • 2
  • 15
  • 17
  • 1
    Once a variable goes out of scope, *don't try to access it*! It's dead and gone (even though the compiler may not have actually cleaned it all up yet). – BoBTFish Feb 26 '13 at 16:42
  • 2
    where is that post about hotel keys... –  Feb 26 '13 at 16:45
  • [It's here.](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope/6445794#6445794) – BoBTFish Feb 26 '13 at 16:47

1 Answers1

5

The code has undefined behaviour, meaning anything can happen including appearing to work, as map_ptr is a dangling pointer as my_map will be destructed at the closing } of the if. The map_ptr will retain the address of my_map but this does not affect the lifetime of my_map in anyway.

hmjd
  • 120,187
  • 20
  • 207
  • 252