When receiving an incoming msessage I receive a correct result when my packet structure has a fixed size array in it, like this
typedef struct inPacket{
int cmd;
int seqNo;
int numbers[100];
} inPacket;
then I call recv like so
char buf[1024];
recv(m_socket, buf, sizeof(buf));
and cast the char array to the packet type
inPacket* p = (inPacket*)buf;
This works fine, I have a full array of ints in the ‘numbers’ field after casting. I cant think why the below doesnt work, when passing in an address at which I want to store the numbers
void func(int* out)
{
inPacket inpacket;
inPacket.numbers = out;
recv(m_socket, (char*)&inpacket, sizeof(inPacket));
}
the ‘numbers’ array is a bad pointer after the call to recv.
The array passed in is allocated by the calling function
int numbers[10];
func(numbers);
What
recvdoes is, it copies data from an internal buffer into the one you supply. So it overwrites the contents of your structure. You also change the array member to some other pointer, which is a no-no. And not only that, you try to set it to an array that is smaller than the existing array, which can lead torecvpossibly overwrite memory outside your new array.You need to do something like this:
Then you call the function like this:
Edit: If a dynamic array is wanted, then the call to
recvhave to be modified, along with the structure: