When buffer
is a char*
, sizeof(buffer)
returns the size of a pointer, rather than the length of the pointed to string. It appears as though the system on which it is compiled uses 4 bytes for a pointer, hence only 4 characters are transmitted. Upon receiving the 4 bytes, handle_receive()
invokes undefined behavior when it attempts to access an invalid index in ip_list
, as the code assumes 3 strings are always extracted from the receive message.
To resolve the problem, explicitly provide the buffer size to sendto()
rather than using sizeof()
. Change:
ret = sendto( s, buffer, sizeof(buffer), 0, ...)
to:
ret = sendto( s, buffer, tx_str.length() + 1, 0, ...)
It may also be worth considering checking input and verifying ip_list
is the expected size before indexing into it.
char[]
and char*
are different types. In the case of char*
, sizeof()
will return the size of a pointer on the given system and not the length of the string pointed to by the pointer. On the other hand, for char[]
, sizeof()
will return the size of the array. For example:
#include <iostream>
int main()
{
char str[] = "123456789ABCDEF";
char* buffer = new char[100];
std::cout << "char[] size = " << sizeof(str) << "\n"
"char* size = " << sizeof(buffer) << std::endl;
}
Results in:
char[] size = 16
char* size = 8