简体   繁体   中英

error in set UI title in MFC

I am trying to change the title of an MFC window as follows:

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?!

Do not use sizeof winTitle as-is.

The _stprintf_s function requires the number of characters , not the number of bytes .

http://msdn.microsoft.com/en-us/library/ce3zzk1k.aspx

Since obviously you're using TCHAR, then the number of characters is as follows:

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

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

Use std::string and std::ostringstream instead of character buffers and 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.

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. 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.

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