У меня есть следующая проблема, в моем коде я пытаюсь построить ответ заголовка в протоколе 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);
функция работает, сервер записывает ответный контент в сокет, но после этого я получаю Segmentation Fault. Я не понимаю, почему.
Функция с рисунком 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");
}
это typo 'strlen (response-> file_content + MAX_HEADER_LENGTH);' -> 'strlen (response-> file_content) + MAX_HEADER_LENGTH;'? –
@iharob Я несколько подозреваю, что это важный источник проблем OP. – WhozCraig
вы правы! Я этого не видел! – kris14an