0

我有这个函数来形成一个 HTTP 请求字符串。运行时,malloc 返回错误:

malloc():大小无效(未排序)中止

下面是我创建的函数,不明白为什么会返回错误。

char* integration_request(char* function, char* lower, char* upper,
        char* segments, char* threads) {

char* start = "GET /integrate/";
char* bs = "/";
char* end = "HTTP/1.1\n\n";
char* request = malloc(sizeof(char) * strlen(start + 1));
strcpy(request, start);

strcat(request, lower);
strcat(request, bs);

strcat(request, upper);
strcat(request, bs);

strcat(request, segments);
strcat(request, bs);

strcat(request,threads);
strcat(request,bs);

strcat(request,function);
strcat(request, end);

return request;
}
4

1 回答 1

0

您分配的内存太少。尝试:

char* request = malloc(strlen(start) +
                       strllen(lower) +
                       strllen(bs) +
                       strllen(upper) +
                       strllen(bs) +
                       strllen(segments) +
                       strllen(bs) +
                       strllen(threads) +
                       strllen(bs) +
                       strllen(function) +
                       strllen(bs) +
                       1);

请注意,sizeof(char)它始终为 1,因此您无需编写它。

于 2021-10-27T03:47:27.830 回答