![](/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.