开发者

Why is there garbage in my TCHAR, even after ZeroMemory()?

开发者 https://www.devze.com 2022-12-30 20:50 出处:网络
I have inherited the following line o开发者_StackOverflow中文版f code: TCHAR temp[300]; GetModuleFileName(NULL, temp, 300);

I have inherited the following line o开发者_StackOverflow中文版f code:

TCHAR temp[300];
GetModuleFileName(NULL, temp, 300);

However, this fails as the first 3 bytes are filled with garbage values (always the same ones though, -128, -13, 23, in that order). I said, well fine and changed it to:

TCHAR temp[300];
ZeroMemory(temp, 300);
GetModuleFileName(NULL, temp, 300);

but the garbage values persisted! Note that after the ZeroMemory() call, all other bytes were zeroed out properly and after GetModuleFileName(), the directory was stored in the buffer properly. It's as if temp was being replaced by temp+3. Could this have something to do with word boundaries?

Can someone explain what is going on and how to fix it?


ZeroMemory works in terms of bytes, whereas you have an array of 300 TCHARs. This makes me assume you're working with widechar (not multi-byte) compilation option.

You should use:

ZeroMemory(temp, 300 * sizeof(TCHAR));

Or in your specific case:

ZeroMemory(temp, sizeof(temp));

However be careful with the latter. It's applicable if temp is an automatic array whose declaration is visible within the function. If it's a pointer whose allocation size is "invisible" for the compiler - sizeof will give just the size of the pointer.

0

精彩评论

暂无评论...
验证码 换一张
取 消