C字符串构建

时间:2015-01-11 13:25:06

标签: c sockets c-strings

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

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

1 个答案:

答案 0 :(得分:4)

你有一个错字,但有趣的是代码正在编译肯定

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

应该是

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

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

response->file_content + MAX_HEADER_LENGTH

传递response->file_content指针递增MAX_HEADER_LENGTH,这是有效的,但非常可能不正确,很可能是分割结果的原因。