I'd like to start with the fact that I'm still learning C++ and some of the things still baffles me.
What I'm trying to accomplish is to build a byte stream to send over a socket. I'm trying to create a packet 1536 bytes in length for a handshake
std::stringstream s1Stream;
char randData[1528], zeroVal[4] = {0, 0, 0, 0};
memset(&randData, 1, sizeof(randData)); // Fill the buffer with data
s1Stream << timestampVal; // 4 bytes
s1Stream << zeroVal; // 4 bytes
s1Stream << randData; // 1528 bytes
When I convert s1Stream to string and check the size() of that string the program says that the size is 1541.
What am I doing wrong?
std::stringstream
's operator<<(char const*)
, which is used here, treats its argument as zero-terminated C-style strings, and your randData
array is not zero-terminated.
Since randData
is not really a C-style string and looks like it could end up containing null bytes, the fix is to use
s1Stream.write(randData, sizeof(randData));
Note that this problem applies with zeroVal
as well, except nothing of zeroVal
will be written to s1Stream
because it is zero-terminated at the first byte.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With