[英]Malloc returning invalid size error when allocating memory
I have this function for forming a HTTP request string.我有这个函数来形成一个 HTTP 请求字符串。 When running, malloc returns an error:
运行时,malloc 返回错误:
malloc(): invalid size (unsorted) Aborted malloc(): 无效大小(未排序)中止
Below is the function I created, cannot understand why this is returning an error.下面是我创建的函数,无法理解为什么会返回错误。
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;
}
You are allocating too little memory.您分配的内存太少。 Try:
尝试:
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);
Notice that sizeof(char)
is always 1 so you don't need to write that.请注意
sizeof(char)
始终为 1,因此您无需编写它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.