访问通过套接字接收的动态分配结构

时间:2014-12-31 06:03:10

标签: c sockets struct

我正在从服务器向客户端传输动态分配的结构。整个结构在客户端接收,但在访问客户端的结构元素时出现分段错误。

服务器代码:

struct structure *struct1 = malloc(sizeof(struct structure)*count);

bytes = send(sockfd, (void*)&struct1, sizeof(struct structure));

客户代码:

struct structure *struct1 = malloc(sizeof(struct structure)*count);

bytes = recv(sockfd, (void*)&struct1, sizeof(struct structure));

3 个答案:

答案 0 :(得分:2)

send()函数原型是

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

第二个参数应为const void *类型。

您的代码中的问题是您没有将指针传递给缓冲区,您将指针传递给指针缓冲。而且,类型转换是错误的。

更改

(void)&struct1

(const void *)struct1

注意:IMO,如果没有演员,这将有效[可能更好]。试一试。

答案 1 :(得分:2)

您正在对指向void指针的指针的地址进行类型转换。做那个

(void*)struct1. 

删除&符号(&)。

答案 2 :(得分:2)

中您无需明确将地址转换为void *。如果包含适当的头文件,最好将其卸载到编译器。

将您的来电重写为

send(sockfd,struct1, sizeof(struct structure));
recv(sockfd, struct1, sizeof(struct structure));

另外作为附注,您应该通过写下以下内容来检查对malloc的调用是否成功:

if(NULL == struct1) {
  /* Error: malloc failed */
}