Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing dynamically allocated structure received through socket

Tags:

c

struct

sockets

I am transferring dynamically allocated structure from server to client.The entire structure is received in client side, but I get segmentation fault when accessing the structure element in 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));
like image 364
Sathiya Avatar asked Apr 26 '26 09:04

Sathiya


2 Answers

The send() function prototype is

ssize_t send(int sockfd, const void *buf, size_t len, int flags);

The second argument should be of type const void *.

The problem in your code is that you're not passing a pointer to the buffer, you're passing a pointer to the pointer to the buffer. Also, the typecasting is wrong.

change

(void)&struct1

to

(const void *)struct1

Note: IMO, this will work [maybe better] without the cast. Give it a try.

like image 88
Sourav Ghosh Avatar answered Apr 28 '26 10:04

Sourav Ghosh


You are typecasting the address of pointer to the void pointer. Make that

(void*)struct1. 

Remove the ampersand(&).

like image 26
Karthikeyan.R.S Avatar answered Apr 28 '26 08:04

Karthikeyan.R.S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!