0

私はある種の HTTP ヘッダーを組み立てたいと思っています (それは私がやっている楽しいプロジェクトです)。しかし、私の問題は、Cでそれを行う方法に関するものです。私は次のような関数を持っています:

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

そして、主にどこかで、次のような応答をしたいと思います。

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

しかし、私はそこにたどり着きません:)文字列を割り当ててコンテンツを挿入する方法には多くの問題があるようです。「BB」フラグに到達しますが、さらに次のようになります。

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

何が間違っていて、どうすれば修正できますか? 私はmallocと C に似た関数に精通していますが、明らかにそれらの専門家ではありません。

ありがとう!

4

1 に答える 1

5

問題はここにあるようです:

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

この場合char*、不適切なサイズの配列を割り当てています。

やったほうがいい:

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

の配列を割り当てるためにchar

于 2013-03-20T08:47:27.010 に答える