Accessing a dynamically allocated structure obtained over a socket
I am passing a dynamically allocated framework from server to client. The whole structure is received on the client side, but I am getting a segmentation error when accessing a structure member on the client side.
server code:
struct structure *struct1 = malloc(sizeof(struct structure)*count);
bytes = send(sockfd, (void*)&struct1, sizeof(struct structure));
client code:
struct structure *struct1 = malloc(sizeof(struct structure)*count);
bytes = recv(sockfd, (void*)&struct1, sizeof(struct structure));
source to share
send()
function prototype
ssize_t send(int sockfd, const void *buf, size_t len, int flags);
The second argument must be of type const void *
.
The problem in your code is that you are not passing a pointer to a buffer, you are passing a pointer to a pointer to a buffer. Also, the typing is wrong.
change
(void)&struct1
to
(const void *)struct1
Note: IMO this will work [possibly better] without streaming. Try it.
source to share
In c you don 't need to explicitly pass the address void *
. Better offload this to the compiler if appropriate headers are included.
Rewrite your send and receive calls as
send(sockfd,struct1, sizeof(struct structure));
recv(sockfd, struct1, sizeof(struct structure));
Also as a side note, you should check if the call was malloc
successful or not by writing something like:
if(NULL == struct1) {
/* Error: malloc failed */
}
source to share