Reputation: 13
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?
Upvotes: 1
Views: 232
Reputation: 16033
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] = "";
Upvotes: 2
Reputation: 171097
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.
Upvotes: 3