开发者

ReadFile Crash in C++

I have a very weird problem. I have been using ReadFile() for reading data from a device connected to the PC over USB. As the data to be read is received in chunks of 64 bytes, always, ReadFile() is called with 64 bytes to read. However, when i have to read a frame less than 64 bytes, occasionally a crash occurs.

I shall give an example of the code written:

//Memory allocation done to read 100 bytes from device - This value is known in prior and he开发者_如何学Gonce memory is allocated exactly
new(100bytes);
// First read of 64 bytes
ReadFile(64)
// Second read of 64 bytes 
ReadFile(64)

-> Here data that would be sent from the device is only 100-64 = 36. Hence, even if I say a read for 64 bytes, there would be no scenario where data greater than 36bytes. hence, this code should work (though i know it is incorrect to allocate less memory and call ReadFile for size greater than the memory allocation).

Question: Could ReadFile() crash if data read is done for more bytes than memory allocation done (though we know what is the exact size of data i need to read)

PS: The reason for such kind of an implementation was a small flaw in design of the code that was developed.


It's entirely possible. Don't lie to APIs, you don't know how they work or if you do they can change. That's part of the point. You don't say how it crashes, but maybe it's an access violation. I don't know why for certain but I can speculate on one possibility. Perhaps ReadFile reads into an intermediate buffer (or buffers) instead of directly into yours (there's a number of reasons it might do this), and later where possible does dword sized copies back into your buffer. It'll still return the right number of bytes read but it could end up copying some "extra" into your buffer. This is fine as long as you've told ReadFile the correct size of your buffer.

Tell the truth.


Well, I doubt that simply the call of ReadFile makes the program crash. Assuming the Windows Readfile function, let me quote the documentation:

If the ReadFile function attempts to read past the end of the file, the function returns zero, and GetLastError returns ERROR_HANDLE_EOF.

Are you handling this error or continuing without checking at all?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜