AfxMessageBox - 访问冲突

时间:2016-11-23 19:47:44

标签: c++ visual-c++ mfc lptstr

以下是正在发生的事情。当我尝试从我的CDialog扩展类中运行AfxMessageBox时,我得到一个错误(见下文)。我用Google搜索了互联网但是做得很短。这是消息框失败的唯一地方,我知道其余代码可以工作(我逐步完成了)。

有谁知道如何解决这个问题?

提前致谢!

AFXMESSAGEBOX打开时出现错误消息:

IsoPro.exe中0x014b4b70处的未处理异常:0xC0000005:访问冲突读取位置0x34333345。

从CDialog

中启动AfxMessageBox的代码
LPTSTR temp;
mainPassword.GetWindowText((LPTSTR)temp,100);
CString cstr;
cstr.Format("mainPassword = %s",temp);
AfxMessageBox(cstr);

显示CDialog的代码:

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

2 个答案:

答案 0 :(得分:3)

问题在于您如何使用GetWindowText

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

您让GetWindowText尝试写入一些未分配的内存,并传递未初始化的temp指针。如果你真的想使用原始输出缓冲区,你应该传递指针到GetWindowText之前为分配空间,例如:

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

但是,由于您使用的是C ++,您可能只想使用字符串 class ,如CString,而不是原始缓冲区,例如:

CString password;
mainPassword.GetWindowText(password);

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

答案 1 :(得分:1)

看起来变量temp是一个未初始化的指针(the definition of LPTSTR是一个char *)。

尝试将temp定义为数组:

TCHAR temp[64];