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 回答