I tried to make a simple MFC GUI application with C++, but it seems to have problem at generating the main window(dialog?). When I'm trying to compile the code, following message shows :
Unhandled exception at 0x00E7A9DC in GUI_Employee_0501.exe: 0xC0000005: Access violation reading location 0xFEFEFF66.
and the break point stops inside winmain.cpp, at pThread->m_pMainWnd->DestroyWindow();. The value of pThread->m_pMainWnd is NULL, which I suspect as the cause of the problem.
Can you specify what is the problem here? I have a sample code and that is very similar to mine but that works, so I truly have no idea what is happening!
#include <afxwin.h>
#include "resource.h"
#include <iostream>
using namespace std;
#pragma comment(linker, "/entry:WinMainCRTStartup /subsystem:console")
CEdit *pFNAME;
CEdit *pLNAME;
CEdit *pSALARY;
CEdit *pDDAY;
CEdit *pMMONTH;
CEdit *pYYEAR;
CComboBox *pGENDER;
CButton *pADD;
CButton *pDELETE;
CButton *pSAVE;
CButton *pLOAD;
class ENTRY_FORM : public CDialog
{
public:
ENTRY_FORM(CWnd* pParent = NULL) : CDialog(ENTRY_FORM::IDD, pParent) { }
enum { IDD = dialog_main };
protected:
virtual void DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); }
virtual BOOL OnInitDialog()
{
CDialog::OnInitDialog();
SetUpInterfacePointers();
return true;
}
void SetUpInterfacePointers(){ ... does its own thing ... }
public:
afx_msg void add() { PRESS_ADD(); }
void PRESS_ADD() { ... does its own thing ... }
DECLARE_MESSAGE_MAP()
};
class Program : public CWinApp
{
public:
Program(){ }
public:
virtual BOOL InitInstance()
{
CWinApp::InitInstance();
cout << "CWinAPP:initInstance" << endl;
ENTRY_FORM dlg;
m_pMainWnd = &dlg;
cout << "mpMainWnd" << endl;
INT_PTR nResponse = dlg.DoModal();
return FALSE;
}
};
//
BEGIN_MESSAGE_MAP(ENTRY_FORM, CDialog)
ON_COMMAND(button_add, add)
END_MESSAGE_MAP()
//
Program theApp;
Change in
InitInstance()
:to
This is because CWinApp::InitInstance should return FALSE only in case of failure, and TRUE if all initialization went OK. In case of failure,
AfxWinMain
will try to destroy window pointed bym_pMainWnd
, which is not possible (it causes Undefined Behaviour) because you assign tom_pMainWnd
a local object (which is destroyed once InitInstance ends).[edit]
S.B Bae - to investigate it further and find a root cause, you will need to debug place where m_pMainWnd should be set to NULL once your dialog ends. This should be in
CWnd::OnNcDestroy()
in wincore.cpp. There is a linepThread->m_pMainWnd = NULL;
which apparently is not being executed in your application.Late to the party, but I saw the exact problem when creating an MFC Dialog application. I found I had accidentally changed the application dialog Style (in Properties) from 'Popup' to 'Child'. Toggling this can consistently toggle this error. 'Overlapped' seems to work just as well as 'Popup'.
https://docs.microsoft.com/en-us/cpp/mfc/reference/styles-used-by-mfc?view=vs-2019#window-styles