简体   繁体   中英

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);

The problem is how you use GetWindowText :

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

You are letting GetWindowText attempt to write to some unallocated memory passing the uninitialized temp pointer. If you really want to use a raw output buffer, you should allocate room for it before passing a pointer to GetWindowText , eg:

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, eg:

CString password;
mainPassword.GetWindowText(password);

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

It looks like the variable temp is an uninitialized pointer ( the definition of LPTSTR is a char *).

Try defining temp as an array instead:

TCHAR temp[64];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM