Using Win32 ReadFile and malloc
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!
Zero-terminate (after the successful call to ReadFile
of course):
sIncoming[dwBytesRead/sizeof(TCHAR)] = 0;
NB: observe the buffer limits.
Complete spliced into your code:
#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);
Edit: Removed the RtlZeroMemory
call as it is not strictly necessary. Just be sure to zero-terminate the received C-string.
sizeof(sIncoming) is the size of a pointer. You want sizeof(TCHAR) * 4097. Or just use calloc.
精彩评论