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));

      

+3


source to share


3 answers


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.

+2


source


You are specifying the address of a pointer to a void pointer. Do it

(void*)struct1. 

      



Remove the ampersand (&).

+2


source


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 */
}

      

+2


source







All Articles