Take the 2-minute tour ×

I have a question about strange return sizes when calling GetUserNameEx(). Maybe someone has encountered this problem already.

I call GetUserNameEx() two times: first to get required buffer size and second to actually populate the buffer.

In the documentation you can read this about the size parameter:

  1. If lpNameBuffer is too small, the function fails and GetLastError returns ERROR_MORE_DATA. This parameter receives the required buffer size, in Unicode characters (whether or not Unicode is being used), including the terminating null character.

    I save this value (required_size) to check with the one returned on success.

  2. On input, this variable specifies the size of the lpNameBuffer buffer, in TCHARs. If the function is successful, the variable receives the number of TCHARs copied to the buffer, not including the terminating null character.

    This one is returned_size.

The strange thing is that if I set Character Encoding in project properties to Not Set, then required_size is 22 and returned_size is 11.

And when I set Charachter Encoding to Use Unicode Character Set, then required_size is 11 and returned_size is 11 too.

Maybe I do not get something, but I expected required_size not to change. Has anyone saw this already?

Thank you.

UPD: here is the code example.

share|improve this question
Post your code. Would be easier to see the problem. –  Dennis Feb 13 '12 at 12:34
Updated the post with the link to the code. –  kishkin Feb 13 '12 at 14:32
add comment

1 Answer

up vote 4 down vote accepted

I repro. Well, it's a bug. It never goes wrong because it asks for a buffer that's twice the required size. You'll get the actual number of characters copied to the buffer on the second call so you do know the real size of the string. I wouldn't try to fix it, there are small odds that it actually uses the buffer before converting the string from Unicode to mbcs. Although I see no evidence of it.

share|improve this answer
Thank you, Hans! –  kishkin Feb 13 '12 at 13:15
Indeed. Don't make Raymond pull out his AppCompat shin again. If there's one code path on one Windows version that actually needs the oversized buffer, then you'd better provide it, even if it's not actually needed in your specific testcase, on your OS version. –  MSalters Feb 13 '12 at 16:21
add comment

Your Answer


