我的动态分配变量用SecureZeroMemory修剪,然后ReadFile用一个短的5char字符串和一堆剩余的正方形填充它。问题是字符串末尾的垃圾字符:
“马达췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍췍”
ReadFile的lpNumberOfBytesRead参数显示字符串是10chars,因为它是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);
谢谢!
答案 0 :(得分:0)
sizeof(sIncoming)是指针的大小。你想要sizeof(TCHAR)* 4097.或者只是使用calloc。
答案 1 :(得分:0)
零终止(当然成功调用ReadFile
之后):
sIncoming[dwBytesRead/sizeof(TCHAR)] = 0;
注意:观察缓冲限制。
完成拼接到您的代码中:
#define BUFSIZE 4096
TCHAR *sIncoming;
sIncoming = (TCHAR *) malloc(sizeof(TCHAR)*BUFSIZE+sizeof(TCHAR));
bSuccess = ReadFile(hPipe,sIncoming ,BUFSIZE*sizeof(TCHAR),&dwBytesRead,NULL);
if(bSuccess)
sIncoming[dwBytesRead/sizeof(TCHAR)] = 0;
free(sIncoming);
编辑:删除了RtlZeroMemory
来电,因为这不是必需的。请务必将收到的C字符串置零。