Is there any mistake to write a code such:
char* sp=(char*)malloc(128);
int x=22;
wsprintf(sp,"%d",x);
cout<<sp;
I am asking specially about security mistakes?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There are a number of “potential” issues here, non of them is actually infinging anything but you may find things not behaving as you expect.
First: wsprintf, as a Win32 API (http://msdn.microsoft.com/en-us/library/windows/desktop/ms647550(v=vs.85).aspx ) is prototyped as:
where
LPTSTRis defined aschar*orwchar_t*depending on the definition or not of theUNICODEsymbol (check your propject settings and / or build commands)Now, in case you are on an ANSI build (no UNICODE) all types are coherent, but there is no check about wsprintf writing more than the 128 char you allocated. If you just write a decimal integer it will have no problem, but if you (of somebody else after you) modify later the “message” and no checks are made, some surprises may arise (like
wsprintf(sp,"This is the number I've been told I was supposed to be expected to be: %d",x);will this still fits the 128 chars?!? )In case you are on a UNICODE build, you allocate 128 char, and write a double-byte string on it. The number 22 will be written as
\x32\x00\x32\x00\x00\x00(3200 is the little-endian coding for 0x0032 that is the wchar_t correponding to the UNICODE 50 that stands for ‘2’).If you give that sequence to cout (that is char based, not wchar_t based) will see the first \x00 as a string terminator and will output … just ‘2’.
To be coherent, you shold either:
charbased types and function (OK malloc and cout, butwsprintfAinstead ofwsprintf)wchar_tbased types and function (malloc(128*sizeof(wchar_t)), wchar_t* andwsprintfW)TCHARbased types (malloc(128*sizeof(TCHAR)), TCHAR* and wsprintf, but definetcoutascoutorwcoutdepending on UNICODE).