0
我有以下问题,在我的代码中,我试图在HTTP
协议中构建响应头。我不明白为什么我的代码不起作用。在缓冲功能构建响应内容,并将其写入套接字文件描述符:C字符串构建
void write_fd(struct http_response* response, int client_socket)
{
int length = strlen(response->file_content + MAX_HEADER_LENGTH);
char response_content[length];
response_content[0] = '\0';
printf("-- Descriptor %i, start responding\n", client_socket);
write_fd_resp_line(response, response_content);
//printf("%s\n", response_content); - "HTTP/1.1 GET OK\n"
write_fd_date(response_content);
//printf("%s\n", response_content); - Segmentation Fault
write_fd_server_name(response_content);
write_fd_con_type(response, response_content);
write_fd_doc_content(response, response_content);
int sended = 0;
int content_length = strlen(response_content) + 1;
int n;
while(sended != content_length) {
n = write(client_socket, response_content + sended, content_length - sended);
if(n <= 0) break;
sended += n;
printf("-- Descriptor - %i, sended %i/%i\n", client_socket, sended, content_length);
}
}
,但是当我变了:
char response_content[length];
到
char* response_content = malloc(length);
功能工作,服务器写入响应内容到套接字,但之后,我得到分段错误。我不明白为什么。
功能的模式write_fd_*
类似于:
void write_fd_resp_line(http_response* response, char* response_content)
{
char *tmp;
char code_str[4];
tmp = (char*) get_status_code_name(response->code);
snprintf(code_str, 4, "%d", response->code);
strcat(response_content, HTTP_VERSION);
strcat(response_content, " ");
strcat(response_content, code_str);
strcat(response_content, " ");
strcat(response_content, tmp);
strcat(response_content, "\n");
}
is this typo'strlen(response-> file_content + MAX_HEADER_LENGTH);' - >'strlen(response-> file_content)+ MAX_HEADER_LENGTH;'? –
@iharob我有些怀疑这是OP难题的重要来源。 – WhozCraig
你是对的!我没有看到! – kris14an