I been working in a project for my Data Networks class and they ask me to concatenate a header like this:
struct ip
{
unsigned long a;
unsigned long b;
unsigned int l;
} IP;
And a message which it’s a char* let’s say “Hello”.
So, I use this method to concatenate those two in a single char*:
memcpy(sendBuf, (void*)&sendHeader, sizeof(sendHeader));
memcpy(&sendBuf[sizeof(sendHeader)], readMessage, lengthMessage);
With lengthMessage being the number of characters of the message +1 which is the null termination character.
So, sendBuf it’s defined like this:
char sendBuf[BUFLEN + 1] // BUF_LEN = 128
And then I put this char* in a queue defined like this:
concurrency::concurrent_queue<char*> IP_in_queue;
So, I want to check if the information it’s correct, so I just check everything:
char* s;
IP_in_queue.try_pop(s);
numbytes = sizeof(s);
// Copy from buf to the header
memcpy( (void*)&readHeader, s, sizeof( IP_PACKET_HEADER_T));
// Copy message part
memcpy( sendedString, &s[sizeof(IP_PACKET_HEADER_T)], numbytes - sizeof(IP_PACKET_HEADER_T));
// Append \0 to the end
sendedString[numbytes - sizeof(IP_PACKET_HEADER_T)] = '\0';
So, before I queue my char*, we know that the size of sendBuf is 129, but when I check the number of bytes after I dequeue it’s way too different, the value of number of bytes it’s 4, but even in that way I get the information right, so I don’t understand that, maybe I missing some important things, but the variable numbytes shouldn’t be at least more?
I hope I made myself clear and maybe someone can explain me this a little bit better.
Thanks
sizeofdoes not tell you the length of the string – it tells you the size of the typechar*, which on a 32-bit machine is 4 bytes. You wantstrlen, the number of bytes in the string.But even that isn’t what you want. Your structure
IPcan have nulls in it, so evenstrlenwon’t give you a correct answer. If you put your string first instead of last you can fix that, but I’d consider that kind of a hack. You should add the size explicitly to the start of your message.