所以我在C中编写了一个app客户端服务器,客户端询问服务器的时间和服务器响应它。我正在使用struct。当我尝试从client.c中的服务器读取时出现分段错误。 我在receiveTimeResponse上遇到分段错误,并试图找出原因。我认为它是因为我没有为char * date分配内存,但我想我做了。
结构:
struct timeStructQuer{
int header[4];
int requestID;
};
struct timeStructResponse{
int header[4];
int requestID;
int length;
char* date;
};
服务器:
int main()
{
//connection here
struct queryStruct myStruct;
read(client_sockfd, &myStruct, sizeof(myStruct));
getCurrentTime(client_sockfd, myStruct);
}
void getCurrentTime(int client_sockfd, struct queryStruct str){
int length;
char* currentTime = malloc(sizeof(char) * 30);
time_t rawtime;
struct tm * timeinfo;
time (&rawtime);
timeinfo = localtime (&rawtime);
length = sprintf (currentTime ,"%s", asctime (timeinfo));
struct timeStructResponse response;
response.date = malloc(sizeof(char) * length);
response.header[0] = 1;
response.header[1] = 0;
response.header[2] = 0;
response.header[3] = 2;
response.requestID = str.requestID;
response.length = length;
response.date = currentTime;
write(client_sockfd, &response, sizeof(response));
}
客户端:
int main()
{
//connection here
sendTimeQuery(sockfd);
receiveTimeResponse(sockfd);
exit(0);
}
void sendTimeQuery(int sockfd){
struct queryStruct myStruct;
int randomN = rand();
myStruct.header[0] = 0;
myStruct.header[1] = 0;
myStruct.header[2] = 0;
myStruct.header[3] = 2;
myStruct.requestID = randomN;
write(sockfd, &myStruct, sizeof(myStruct));
}
void receiveTimeResponse(int sockfd){
struct timeStructResponse response;
response.date = malloc(sizeof(char) * 30);
printf("seg2");
read(sockfd, &response, sizeof(response));
printf("Current time: %s", response.date);
}
答案 0 :(得分:0)
read(sockfd, &response, sizeof(response));
将使用无效值覆盖先前已分配的response.data
指针。问题是你不能传递指针(实际上你可以,但指针值在另一侧无效)。您需要传输他们指向的数据。所以写应该是这样的:
/* TODO check write results... */
write(client_sockfd, &response.header, sizeof(response.header));
write(client_sockfd, &response.requestID, sizeof(response.requestID));
write(client_sockfd, &response.length, sizeof(response.length));
write(client_sockfd, response.date, response.length);
并且如下所示:
/* TODO check read and malloc results, length, and date is properly null-terminated... */
read(sockfd, &response.header, sizeof(response.header));
read(sockfd, &response.requestID, sizeof(response.requestID));
read(sockfd, &response.length, sizeof(response.length));
response.date = (char *) malloc(response.length);
read(sockfd, response.date, response.length);