[英]error in set UI title in MFC
I am trying to change the title of an MFC window as follows: 我试图按如下方式更改MFC窗口的标题:
BOOL CameraUI::OnInitDialog()
{
// set ui title
TCHAR wintitle[100];
_stprintf_s(wintitle, sizeof wintitle, _T("Camera %u"), (UINT) getSerialNumber());
SetWindowText(wintitle);
return TRUE;
}
When I debug I get this error at the end of the function: 当我调试时,在函数末尾出现此错误:
Run-Time Check Failure #2 - Stack around the variable 'wintitle' was corrupted.
I am using MSVC 2008. What am I doing wrong?! 我正在使用MSVC2008。我在做什么错?!
Do not use sizeof winTitle
as-is. 不要
sizeof winTitle
原样使用sizeof winTitle
。
The _stprintf_s
function requires the number of characters
, not the number of bytes
. _stprintf_s
函数需要characters
数,而不是bytes
。
http://msdn.microsoft.com/en-us/library/ce3zzk1k.aspx http://msdn.microsoft.com/en-us/library/ce3zzk1k.aspx
Since obviously you're using TCHAR, then the number of characters is as follows: 由于显然您使用的是TCHAR,因此字符数如下:
sizeof(winTitle) / sizeof(winTitle[0])
or 要么
sizeof(winTitle) / sizeof(TCHAR)
A TCHAR in the MS world is either going to be 1 byte (if the build is MBCS) or 2 bytes (which is Unicode). MS世界中的TCHAR将是1个字节(如果内部版本为MBCS)或2个字节(即Unicode)。
Assuming you're using Unicode, by just stating sizeof winTitle
, you are specifying that your array can fit a maximum of 200 characters, but that is not true (display what sizeof winTitle
gives you, and you will see it is 200). 假设您使用的是Unicode,只需声明
sizeof winTitle
,即可指定数组最多可容纳200个字符,但这不是正确的(显示sizeof winTitle
给您的sizeof winTitle
,您将看到它为200)。
Use std::string
and std::ostringstream
instead of character buffers and sprintf. 使用
std::string
和std::ostringstream
代替字符缓冲区和sprintf。 This way you can avoid buffer overruns by having these classes manage memory for you. 这样,您可以通过让这些类为您管理内存来避免缓冲区溢出。 The only time you'll need to interact with c-style strings directly is when interacting with Win32 functions.
与Win32函数交互时,唯一需要直接与c样式字符串交互的时间。
std::ostringstream output;
std::string wintitle;
output << "Camera " << (UINT) getSerialNumber();
wintitle = output.str();
SetWindowText(wintitle.c_str());
return TRUE;
There is a templated overload of _stprintf_s
that does not require a buffer size parameter. _stprintf_s
有模板重载,不需要缓冲区大小参数。 You can write the erroneous line as 您可以将错误行写为
_stprintf_s(wintitle, _T("Camera %u"), (UINT) getSerialNumber());
The template will automatically deduce the correct length of the destination buffer and protect you from passing the wrong buffer size. 该模板将自动推断出目标缓冲区的正确长度,并防止您传递错误的缓冲区大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.