Dan G Dan G - 13 days ago 5
C++ Question

AfxMessageBox - Access violation

Here is what is going on. When I try and run an AfxMessageBox from my CDialog extension class, I get an errror (see below). I've googled the internet but come up short. This is the only place the messagebox fails, and I know the rest of the code works (I stepped through it).

Does anyone know how to fix this?

Thanks in advance!

Error message when AFXMESSAGEBOX opens:

Unhandled exception at 0x014b4b70 in IsoPro.exe: 0xC0000005: Access violation reading location 0x34333345.

Code to launch AfxMessageBox, from within CDialog

LPTSTR temp;
mainPassword.GetWindowText((LPTSTR)temp,100);
CString cstr;
cstr.Format("mainPassword = %s",temp);
AfxMessageBox(cstr);


Code to display CDialog:

CEnterpriseManagementDialog* emd = new CEnterpriseManagementDialog();
emd->Create(IDD_ENTERPRISE_MANAGEMENT_DIALOG);
emd->ShowWindow(SW_SHOW);

Answer

The problem is how you use GetWindowText:

LPTSTR temp;
mainPassword.GetWindowText((LPTSTR)temp,100);

You are letting GetWindowText attempt to write to some unitialized memory passing temp. If you really want to use a raw output buffer, you should preallocate room for it before passing a pointer to GetWindowText, e.g.:

TCHAR temp[100];
mainPassword.GetWindowText(temp, _countof(temp));
// NOTE: No need to LPTSTR-cast

But, since you are using C++, you may want to just use a string class like CString, instead of raw buffers, e.g.:

CString password;
mainPassword.GetWindowText(password);

CString msg;
msg.Format(_T("mainPassword = %s"), password.GetString());
// or you can just concatenate CStrings using operator+ ... 
AfxMessageBox(msg);