Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ stringstream adding extra bytes

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?

like image 242
Sk1ppeR Avatar asked Dec 12 '22 01:12

Sk1ppeR


1 Answers

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.

like image 73
Wintermute Avatar answered Jan 02 '23 10:01

Wintermute