c++ - AfxMessageBox - 访问冲突

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

这是正在发生的事情。当我尝试从 CDialog 扩展类运行 AfxMessageBox 时,出现错误(见下文)。我用谷歌搜索过互联网,但没有找到答案。这是消息框唯一失败的地方,我知道其余代码可以工作(我单步执行了它)。

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

提前致谢!

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

最佳答案

问题是你如何使用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);

关于c++ - AfxMessageBox - 访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40772975/

相关文章:

c++ - skipper 在 boost::spirit 中不起作用

c++ - 使用可变参数模板构建元组

c++ - throw() (即 __declspec(nothrow)) 是否在 Visual C++ 中提供了真正的好处?

c++ - 如何使用命名空间系统;使用 VC++ 在 MFC 应用程序中

c++ - 连接 MFC 和命令行

c++ - 如何在 C++ 中初始化双指针结构数组?

c++ - 如何避免 C++11 中 <thread> 抛出的异常?

c - int **p 的奇怪行为?

c++ - 当文件路径名超过 255 个字符时,如何在 Windows 中使用 MFC 创建文件?

c++ - 在C++/MFC中停止和启动DirectX声音合成器时弹出/单击