[RESOLVED] _stprintf_s - Out of bound access
Code:
WORD iDay;
TCHAR text[3];
_stprintf_s(text, sizeof(text), _T("%d"), iDay);
The above piece of code giving some out of bound access error by some Static code analyser. The iDay is used for Date: ie: 1 - 31.
What should be the proper check to avoid this instead of using a CString in place or TCHAR. ?
Re: _stprintf_s - Out of bound access
1. It should be _countof(text) instead of sizeof(text).
From MSDN:
Quote:
sizeOfBuffer
Maximum number of characters to store.
2. WORD means unsigned short and its max value is 65535 which requires at least 6-character buffer for formatting (5 for digits + 1 for terminating NULL)
Re: _stprintf_s - Out of bound access
Another quick solution would be
Code:
WORD iDay;
TCHAR text[3];
if(iDay <= 31)
_stprintf_s(text, sizeof(text), _T("%d"), iDay);
Correct ?
Re: _stprintf_s - Out of bound access
Quote:
Originally Posted by
hypheni
Another quick solution would be
No, that is not a solution. Read up on what a TCHAR is and what sizeof(TCHAR) gives you. That sizeof(text) isn't what you think it is.
Regards,
Paul McKenzie
Re: _stprintf_s - Out of bound access
Quote:
Originally Posted by hypheni
Correct ?
Still wrong! :eek:
I wonder why you are searching for "quick" solution instead of a correct and clean one! :confused:
What is wrong with MFC CString?
Why do you pass in a wrong value of the text buffer size? :confused:
Re: _stprintf_s - Out of bound access
Okay, Correct I missed it.