C弦构建

C strings building

我有以下问题,在我的代码中,我试图在 HTTP 协议中构建响应 header。我不明白为什么我的代码不起作用。函数在缓冲区中构建响应内容,并将它们写入套接字文件描述符:

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] = '[=10=]';

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

你有一个错字,但有趣的是代码确实在编译

int length = strlen(response->file_content + MAX_HEADER_LENGTH );

应该是

int length = strlen(response->file_content) + MAX_HEADER_LENGTH;

编译代码的原因是因为这意味着什么

response->file_content + MAX_HEADER_LENGTH

传递递增 MAX_HEADER_LENGTHresponse->file_content 指针,这是有效的,但很可能不正确,并且很可能是分段错误的原因。