gpt4 book ai didi

c - 使用套接字读取 char* 时出现段错误

转载 作者:行者123 更新时间:2023-11-30 16:34:22 25 4
gpt4 key购买 nike

所以我正在用 C 语言编写一个应用程序客户端-服务器,客户端向服务器询问时间,服务器用它进行响应。我正在使用 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);
}

最佳答案

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

关于c - 使用套接字读取 char* 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49349139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com