Win32 MessageBox切断文本

时间:2014-02-05 20:24:46

标签: winapi text messagebox

当尝试使用MessageBox函数显示win32对话框时,文本似乎被切断了,但奇怪的是,只有在构建发布时才会发生这种情况,这让我感到非常困惑。

代码发生在:

wchar_t filepath[ MAX_PATH ];
GetModuleFileName( NULL, filepath, MAX_PATH );

wchar_t* fnp = PathFindFileName(filepath);

wchar_t filename[MAX_PATH];
swprintf(filename, MAX_PATH, L"%ls", fnp);
printf("%ls", filename);
wchar_t* pwc;
pwc = wcsstr(filename,L".exe");
wcsncpy(pwc,L"_real.exe\0",10);

if(!file_exists(filename)){
    wchar_t buff[] = L"unable to start because %ls cannot be found.";
    wchar_t say[MAX_PATH+sizeof(buff)-3];
    swprintf(say, wcslen(say), buff, filename);
    MessageBoxW(NULL, say, L"Error", MB_OK | MB_ICONERROR);
    return 0;
}

1 个答案:

答案 0 :(得分:0)

主要问题是你写wcslen(say)的地方。在您编写它时,say尚未初始化,因此wcslen(say)会调用UB。你打算写sizeof(say)/sizeof(wchar_t)

最重要的是,sizeof(buff)的大小为char个单位。但阵列有wchar_t个单位。所以代码是错误的。

你想要这样的东西:

wchar_t buff[] = L"unable to start because %ls cannot be found.";
wchar_t say[MAX_PATH + sizeof(buff)/sizeof(wchar_t) - 3];
swprintf(say, sizeof(say)/sizeof(wchar_t), buff, filename);