I'm failing to read more than 65536 bytes into a buffer from a file using boost::asio::windows::stream_handle asynchronously.
Starting from 65537th byte the buffer contains the the data from the very beginning of the file, rather than the expected data.
Here is a code example, which reproduces the issue:
auto handle = ::CreateFile(L"BigFile.xml", GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, nullptr);
boost::asio::io_service ios;
boost::asio::windows::stream_handle streamHandle(ios, handle);
const auto to_read_bytes = 100000;
char buffer[to_read_bytes];
boost::asio::async_read(streamHandle, boost::asio::buffer(buffer, to_read_bytes), [](auto &ec, auto read) {
std::cout << "Bytes read: " << read << std::endl;
});
ios.run();
auto bufferBegin = std::string(buffer, 38);
auto bufferCorrupted = std::string(buffer + 65536, 38); // <- it contains bytes from the beginning of the file
std::cout << "offset 0: " << bufferBegin << std::endl;
std::cout << "offset 65536: " << bufferCorrupted << std::endl;
::CloseHandle(handle);
That code produces an output:
> Bytes read: 100000
> offset 0: <?xml version="1.0" encoding="UTF-8"?>
> offset 65536: <?xml version="1.0" encoding="UTF-8"?>
The source file is bigger than 65536.
This is reproducible with boost 1.61 + VS2015. Also that issue was in boost 1.55 + VS2010.
Operating systems are: Windows 7 and Windows Server 2008R2.
My questions are:
1. Is that the known limitation in boost::asio or in WinAPI?
2. If it is the known limitation, what would be the safe size of the buffer to read data? Is it safe to have a buffer of size 65536, or it should be smaller?
std::stringwhich allocates memory on heap, instead of usingchar buffer[100000];which allocates on stack. Or just useto_read_bytes = 4096it doesn't get faster if you increase that buffer size.