Re: Unicode Problems (TCHAR, wchar_t, functions)
jpshortstuff <jpshortstuff@discussions.microsoft.com> wrote:
This has nothing to do with TCHAR or UNICODE, it would be equally
broken with plain chars. You are allocating a buffer of length 2,
but are stuffing a much longer string into it. Classic buffer
overflow.
Ok, looking back, 2 was horribly wrong, even my char version used 3.
3 wouldn't help any. You need enough space to hold
"c:\\Folder\\log.txt", which comes to 18 characters.
As far as I can see, even in ASCII, %systemdrive% will never be more
than two characters long, so allowing an extra one of the terminating
null that gives a max length of 3.
But you aren't just putting the drive letter into the buffer. You are
also appending the file name to it. Read the documentation on strcat,
carefully. Where do you expect it to get extra memory from - thin air?
You are misinterpreting the bytes of an ASCII string as if it were a
Unicode string. Every two bytes (two characters in the narrow string)
are taken to be one Unicode character. In particular, your ASCII
string is terminated by one zero byte, but a Unicode string is
expected to be terminated by two zero bytes (one NUL Unicode
character). So (TCHAR*)sysdrive is, in effect, an unterminated
string.
I knew this was the structure of Unicode, I assumed that this
difference would all be sorted when I type casted it to a wchar_t.
You didn't cast char to wchar_t. You cast char* to wchat_t*. The bytes
in the buffer didn't magically change as a result - you are just
interpreting them differently (and incorrectly). Consider:
Apple* pa = new Apple;
Orange* po = (Orange*)pa;
Do you expect this code to "convert" Apple to Orange somehow?
Evidently, type casting is a lot less comprehensive then I thought.
I can't even begin to imagine what you expected it to do.
There's nothing wrong with this code. I can only assume that argv[1]
is not in fact equal to /?
Again, I have a non-unicode that works fine when I type "MyProgram
/?" at the command-line, but this version doesn't do it.
Well, debug it, figure out why.
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925