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