-2

I have functions to load and get Icon from files as follows:

std::map<wstring, HICON> m_map_icons;

void WindowSysTray::_loadIconFromFiles()
{
    ...
    for (int i = 0; i < 3; ++i) {
        wstring temp = path + trayList[i];
        HICON hIcon = NULL;
        Gdiplus::Bitmap bitmap(temp.c_str(), false);
        bitmap.GetHICON(&hIcon);
        pair<wstring, HICON> _pair = make_pair(trayList[i], hIcon);
        m_map_icons.insert(_pair);
    }
}

HICON WindowSysTray::getIconFromFile(const wchar_t* iconPath)
{
    auto iter = m_map_icons.find(wstring(iconPath));
    if (iter == m_map_icons.end()) {
        return NULL;
    }
    else {
        return iter->second; // ---Issue here---
    }
}

...
hIcon = getIconFromFile(L"tray.png");
if (hIcon)
{
    TrayIcon.SetIcon(hIcon);
}
...

When I invoke getIconFromFile function, it sometimes crashes while returning value at the end of the function:

return iter->second;

I verified and make sure that I loaded Icon before by invoking _loadIconFromFiles function.

Does anyone know what is the possible root cause of this issue?

Ilya
  • 4,583
  • 4
  • 26
  • 51
CH4
  • 85
  • 2
  • 13
  • 1
    Maybe the instance of `WindowSysTray` is not valid? Post a [mcve] to show how you created instances of this class. – PaulMcKenzie Sep 26 '18 at 10:31
  • Doesn't seem to be anything wrong with the code posted. How do you know it crashes when returning the value? – john Sep 26 '18 at 10:33
  • I'd ask a debugger. – YSC Sep 26 '18 at 10:37
  • Please, put the `HICON` into a smart pointer with custom deleter (`DestroyIcon()`). – Swordfish Sep 26 '18 at 10:39
  • @john It crashed and create a .dmp file. I also put some logs to test this. Actually, it does not always crash. – CH4 Sep 26 '18 at 10:39
  • 2
    @CuongHuynh Crashing on exit from a function is sometimes an indication of stack corruption, but there's no evidence of that in the posted code. – john Sep 26 '18 at 10:43
  • [mcve] that crashes or it didn't happen. – Swordfish Sep 26 '18 at 10:43
  • 1
    @CuongHuynh You only posted class code -- that is not enough. We have no idea when, where, or how `WindowSysTray` instances are created. If you are using an invalid `WindowSysTray` instance, then anything done within that invalid instance leads to undefined behavior. – PaulMcKenzie Sep 26 '18 at 10:43

1 Answers1

0

m_map_icons.find() could go wrong. This might be the case if m_map_icons is empty. You can start WindowSysTray::getIconFromFile with a check: if (m_map_icons.size() == 0) return 0;

HanT
  • 141
  • 4