MicroCheapFx
MicroCheapFx

Reputation: 402

std::map iteration turns wrong on first run

I have a std::map to store pointers to objects associated with their respective ID. When I loop on the map to get the content of it, I get a wrong return on first try, but a correct one on next tries:

class session_list {
private:
    ...
  static std::map<uint, session*> session_list;
    ...
public:
    ...
  static void add_exclusive_session(uint id, session& session);
    ...
  std::map<uint, session*>& get_session_list() ;
};
std::map<uint, core_base_session*>& core_session_list::get_session_list() {
    return session_list;
}

void session_list::add_exclusive_session(uint id, session& session) {
    guard g(mutex);
    if (session.disconnect_reason != core_sd_connected)
         return;
    session * previous_session = get_session(id, g);
    session_list.emplace(id, &session);
    if ((previous_session != nullptr)
        &&(previous_session != &session)) {
    previous_session->disconnect(core_sd_peer_duplicated);
  }
}
std::map<uint, session*> session_list =
    session.parent.session_list->get_session_list();
for ( auto& it: session_list) {
    printf("\n\tSESSION N° %d \t %p" , it.first, it.second);
}

It dumps this :

2016-08-18 14:57:23.103881 [info] DBG_

        SESSION N° 1402969504    0x7efc400008c0 <=== APPEARS TWICE
        SESSION N° 574745422     0x1a469f0
        SESSION N° 1402969504    0x7efc400008c0 <=== APPEARS TWICE
        SESSION N° 1502939797    0x7efc48000ca0
        SESSION N° 1510611043    0x7efc3c000ca0
2016-08-18 14:57:38.245280 [info] DBG_

        SESSION N° 2011917896    0x7efc44000ca0 <=== APPEARS NOT ON FIRST TRY
        SESSION N° 574745422     0x1a469f0
        SESSION N° 1402969504    0x7efc400008c0
        SESSION N° 1502939797    0x7efc48000ca0
        SESSION N° 1510611043    0x7efc3c000ca0

Any idea?

Upvotes: 1

Views: 94

Answers (1)

NPE
NPE

Reputation: 500227

So what we appear to see here is that a std::map object contains two identical keys. Let's enumerate the possibilities that would explain this behaviour (from least likely to most likely):

  • your compiler's std::map is fundamentally broken and allows multiple identical keys;
  • you have an undefined behaviour somewhere in your code that corrupts session_list;
  • the first sequence of SESSION N° lines is produced by the code in question getting executed more than once, e.g.

    # run 1
    SESSION N° 1402969504    0x7efc400008c0 <=== APPEARS TWICE
    # run 2
    SESSION N° 574745422     0x1a469f0
    SESSION N° 1402969504    0x7efc400008c0 <=== APPEARS TWICE
    SESSION N° 1502939797    0x7efc48000ca0
    SESSION N° 1510611043    0x7efc3c000ca0
    

My money's on the last one. It's hard to tell how likely it is without seeing more of your code.

Upvotes: 1

Related Questions