I am trying to convert wchar_t
to char
using wcstombs
. And it works fine if only 1 value is converted but when more than 1 value is converted it gives unexpected results. These are two wchar_t
values which I want to convert:
wchar_t szBuf[BUFF_LEN];
wchar_t szBuf1[BUFF_LEN];
and converting using wcstombs
:
char user[]="";
int length = wcstombs(user,szBuf,250);
char pass[]="";
int length1 = wcstombs(pass,szBuf1,250);
say if I have alice in szBuf
and alice123 in szBuf1
then pass
will give the correct value but user
will have a value like aalice123 . What is the error?
You're invoking Undefined Behaviour, because you're writing outside of the buffer bounds. Your user
and pass
buffers are each of length 1
(they're arrays initialised by a copy of ""
). So you're happily writing to random memory and anything could happen.
Your destination buffers are too small.
char user[] = "";
equals char user[1] = "";
. This means that you will write to unallocated space and it is undefined behaviour . This is very bad, because there are no guarantees what will happen.
Specify size for your destionation buffers: char user[250] = "";
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.