phuclv
phuclv

Reputation: 41962

MFC assertion failed when debugging

I'm not familiar with MFC but currently I must continue a project that was written in MFC. Now I'm having trouble with the following line when debugging

m_hIcon = AfxGetApp()->LoadIcon (IDR_MAINFRAME);

It always stops after the error "Assertion Failed: at afxwin1.inl". If I put a breakpoint there I saw a NULL icon handle. I tried running in release mode and it worked just fine although the handle is still NULL. I've read this question but my program is not a static library. It's a program that use a dll to connect to a CAN bus device. And the resource IDR_MAINFRAME is already in the project. It contains the default MFC icons. How can I solve this problem?


I've tried debugging and see that pModuleState changes between the first load program name call and the second load icon call. The first call returns successfully because pModuleState points to an object that has valid handle. But in the icon load call, pModuleState points to some object contains NULL handle. I also tried putting AFX_MANAGE_STATE(AfxGetStaticModuleState( )); right above the LoadIcon() call but the problem still arises


I've known the cause of this problem

UINT __cdecl RunCPRead(LPVOID pParam)
{
    CMyDlg *thisclass = (CMyDlg *)pParam;

    while (thisclass->m_Start)
    {   
        thisclass->GetData();
    }
    return 0;
}

AfxBeginThread(&RunCPRead, this, THREAD_PRIORITY_NORMAL, 0, 0, NULL);

After the GetData() call in RunCPRead, the control flows directly to CMyDlg's contructor although there's no object being created or copied

CMyDlg::CMyDlg(CWnd* pParent /*=NULL*/)
    : CDialog(CMyDlg::IDD, pParent)
{
    m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

and then fails at the assignment to m_hIcon with the error "access violation while reading". I've seen the disassembly, it was the line mov dword ptr [esi+90h], eax and it's inherently a write to memory.

I don't know why. How can I solve this?

Upvotes: 1

Views: 5228

Answers (3)

maanijou
maanijou

Reputation: 1067

Assertion Errors in MFC usually happens when wrong settings are set.

go to project settings > linker > System and change subsystem to (/SUBSYSTEM:WINDOWS) this solution solved my own problem.

Upvotes: 0

ScottMcP-MVP
ScottMcP-MVP

Reputation: 10425

By default MFC uses the resource handle of the main application, not of the DLL. If you are making the call in the DLL then add this line at the start of the exported DLL function:

AFX_MANAGE_STATE(AfxGetStaticModuleState( ));

There is more information about this here:

http://msdn.microsoft.com/en-us/library/ba9d5yh5(v=vs.110).aspx

Upvotes: 0

leixure
leixure

Reputation: 41

The MFC code need the correct module handle to load the resource. Please try to read Afx*G/S*etResourceHandle.

Upvotes: 0

Related Questions