使用 Win32 ReadFile 和 malloc
我的动态分配变量用 SecureZeroMemory 进行修剪,然后 ReadFile 用一个短的 5 个字符字符串和一堆剩余的方块填充它。问题是字符串末尾的垃圾字符:
“motor췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍”
ReadFile 的 lpNumberOfBytesRead 参数显示字符串为 10 个字符,可能是因为它是 Unicode?
有人可以帮我看看如何删除这些尾随的垃圾字符吗?有没有像 ZeroMemory 这样的函数可以清除它们?
TCHAR *sIncoming;
sIncoming = (TCHAR *) malloc(sizeof(TCHAR) * 4096 + sizeof(TCHAR));
RtlZeroMemory(sIncoming ,sizeof(sIncoming));
// (a string array with no characters in it: "")
bSuccess = ReadFile(hPipe,sIncoming ,BUFSIZE*sizeof(TCHAR),&dwBytesRead,NULL);
// Now the string array has the incoming string plus extra characters in it:
// "motor췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍"
free(sIncoming);
谢谢!
My dynamically allocated variable is trimmed with SecureZeroMemory, then ReadFile populates it with a short 5char string and a bunch of remaining squares. The problem is the junk characters at the end of the string:
"motor췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍"
The ReadFile's lpNumberOfBytesRead parameter shows the string is 10chars, prbly because it's Unicode?
Can someone help show me how to remove these trailing junk characters? Is there a function like ZeroMemory that clears them?
TCHAR *sIncoming;
sIncoming = (TCHAR *) malloc(sizeof(TCHAR) * 4096 + sizeof(TCHAR));
RtlZeroMemory(sIncoming ,sizeof(sIncoming));
// (a string array with no characters in it: "")
bSuccess = ReadFile(hPipe,sIncoming ,BUFSIZE*sizeof(TCHAR),&dwBytesRead,NULL);
// Now the string array has the incoming string plus extra characters in it:
// "motor췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍"
free(sIncoming);
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
零终止(当然是在成功调用
ReadFile
之后):注意:观察缓冲区限制。
完全拼接到您的代码中:
编辑:删除了
RtlZeroMemory
调用,因为它并不是绝对必要的。只要确保接收到的 C 字符串以零结尾即可。Zero-terminate (after the successful call to
ReadFile
of course):NB: observe the buffer limits.
Complete spliced into your code:
Edit: Removed the
RtlZeroMemory
call as it is not strictly necessary. Just be sure to zero-terminate the received C-string.sizeof(sIncoming) 是指针的大小。您需要 sizeof(TCHAR) * 4097。或者只使用 calloc。
sizeof(sIncoming) is the size of a pointer. You want sizeof(TCHAR) * 4097. Or just use calloc.