所以我正在用C编写一个应用程序客户端-服务器,客户端向服务器询问时间,服务器响应它。我正在使用结构来做。当我尝试从client.c中的服务器读取时,我遇到分段错误。我在接收时间响应时遇到分段错误,并试图找出原因。我认为这是因为我没有为 char* 日期分配内存,但我想我做到了。
结构:
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);
}
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);