Click to See Complete Forum and Search --> : sending a struct through a socket


Serendipitus
November 7th, 2009, 05:50 PM
I have been trying to send a struct through a UDP socket. however i am segfaulting on the recieve side. my struct looks like this
typedef struct myData
{
std::string message;
int seq;
}Data;

i send the struct like so:
sendto(sockfd, (const char*)&mystruct, sizeof(mystruct), 0, (struct sockaddr*)&destSock, c)

and i recive like so:
char buf[MAXRECV];
recvfrom(sockfd, buf, sizeof(Data), 0, (struct sockaddr*)&sourceSock, &c);
(Data) buf;

the sendto and recvfrom calls do not throw an error so something else must be going wrong. i know its generally a bad idea to send structs through sockets but considering im doing this all on one machine it shouldnt matter, correct?

ZuK
November 8th, 2009, 09:04 AM
i know its generally a bad idea to send structs through sockets but considering im doing this all on one machine it shouldnt matter, correct?
I don't see a general problem to send structs. But the members of the struct have to be POD types and must not be pointers.
Your problem is that you try to send an instance of a struct that contains a std::string member.
The string holds only a pointer to it's dynamically allocated data. ( that you do not transmit ).
When you access that received string you basically dereference the strings data pointer that now points to an illegal memory location --> boom.
Kurt

hoxsiew
November 8th, 2009, 09:15 AM
I was in the process of replying, but ZuK pretty much nailed it.

Serendipitus
November 8th, 2009, 02:49 PM
Ah. That makes too much sense. :). So if I change the std::string to a char[] and send the string that way I should have no problems correct? I would test it out myself but I am currently at work.