2013-03-20 2 views
0

HTTP 헤더 (일종의 재미있는 프로젝트 수행 중)를 정렬하려고합니다.c 문자열을 어셈블하고 참조로 반환 (malloc 및 string.h 함수 사용)

char *resp; 
assembleResponse(&resp, 200, 500, "text/html"); 
printf("assembled response: %s", resp); 

그러나 I : I는 응답과 같이 만들고 싶어 주요 어딘가에

void assembleResponse(char **response, const unsigned short code, const unsigned long length, const char *contentType) 
{ 
    char *status; 
    char *server = {"Server: httpdtest\r\n"}; 
    char *content = malloc(17 + strlen(contentType)); 
    char *connection = {"Connection: close"}; 

    printf("AA"); 

    strcpy(content, "Content-type: "); 
    strcat(content, contentType); 
    strcat(content, "\r\n"); 

    printf("BB"); 

    switch (code) 
    { 
    case 200: 
     //200 Ok 
     status = malloc(sizeof(char) * 18); 
     //snprintf(status, 17, "HTTP/1.1 200 Ok\r\n"); 
     strcpy(status, "HTTP/1.1 200 Ok\r\n"); 
     break; 
    } 

    printf("CC"); 

    unsigned int len = 0; 
    len += strlen(status); 
    len += strlen(server); 
    len += strlen(content); 
    len += strlen(connection); 

    printf("DD"); 

    response = malloc(sizeof(char) * (len + 5)); 
    strcpy(*response, status); 
    strcat(*response, server); 
    strcat(*response, content); 
    strcat(*response, connection); 
    strcat(*response, "\r\n\r\n"); 

    printf("EE"); 
} 

그리고 :하지만 내 문제는 C에서 나는이 같은 기능을 가지고 수행하는 방법에 대한 자세한입니다 거기에 꽤 도착하지 :) 거기에 문자열을 할당하고 그들에게 내용을 삽입하는 방법에 많은 문제가있는 것 같습니다. 나는 "BB"깃발을 얻는다. 그러나 나는 더 알아 듣는다 :

malloc: *** error for object 0x104b10e88: incorrect checksum for freed object - object was probably modified after being freed. 

나는 무엇을 잘못하고 그것을 고치는 법? 나는 malloc과 C와 같은 기능을 가지고 있지만 그것들에 대한 전문가는 분명하지 않다.

감사합니다.

답변

5

문제는 여기에있을 것 같다 :이 경우

response = malloc(sizeof(char) * (len + 5)); 

당신이 잘못된 크기 char*의 배열을 할당하고 있습니다.

당신은 수행해야합니다

*response = malloc(sizeof(char) * (len + 5)); 

char의 배열을 할당하기 위해.