![](/img/trans.png)
[英]C: Trying to free malloc'd char array returned from function results in an error
[英]Free a char* that was malloc'd by a function
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* mkstr(char str1[], char str2[])
{
char* out = malloc(sizeof(*str1) + sizeof(*str2) + 1);
strcpy(out, str1);
strcat(out, str2);
return out;
}
int main()
{
char* str = mkstr("i use ","arch btw");
printf("%s\n",str);
}
当main()
调用mkstr()
时, mkstr()
将out
调用char*
。 我怎样才能从这段代码中正确地free(out)
? 我可以保留它,还是操作系统会释放 malloc 的空间?
这是最好的方法,还是有更好的方法?
我在 Linux 上(如果相关的话)。
sizeof(*x)
是平台上指针的大小。 在 32 位平台上通常为 4,在 64 位平台上通常为 8。
要获取字符串的长度,您需要使用strlen
function。
更正的代码:
char* mkstr(char str1[], char str2[])
{
// you need to use strlen to get the length of a string
char* out = malloc(strlen(str1) + strlen(str2) + 1);
strcpy(out, str1);
strcat(out, str2);
return out;
}
int main()
{
char* str = mkstr("i use ","arch btw");
printf("%s\n",str);
free(str); // simply free str
}
在退出应用程序之前,应该释放每个分配 object 的堆(大多数现代操作系统都会管理堆分配,即使您在退出应用程序时没有释放它们)。 顺便说一句,释放堆资源是一个很好的做法。
mkstr
function 的参数应该是(const char *str1, const char *str2)
而不是(char str[], char str2[])
。calloc
代替malloc
以获得更好的安全性。strlen
function 来确定字符串的长度,而不是sizeof
。void
或(int argc, char const **argv)
设置为main
function 的参数。#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *mkstr(const char *str1, const char *str2)
{
char *out = calloc(sizeof(char) * (strlen(str1) + strlen(str2) + 1), sizeof(char));
strcpy(out, str1);
strcat(out, str2);
return out;
}
int main(int argc, char const **argv)
{
char *str = mkstr("i use ", "arch btw");
printf("%s\n", str);
free(str); // freed the heap allocated resource before exiting
return 0;
}
无论如何,在阅读了所有答案之后,这是新代码。
char* mkstr(char str1[], char str2[])
{
char* out = malloc(strlen(str1) + strlen(str2) + 1);
strcpy(out, str1);
strcat(out, str2);
return out;
}
int main()
{
char* str = mkstr("i use ","arch btw");
printf("%s\n",str);
free(str);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.