我正在玩弄我的自定义字符串库,顺便说一句,这很糟糕,但我这样做是为了获得经验。
无论如何,我有一些函数可以为 String*
分配内存块以供使用,并且工作正常。当调用 string_delete(string*)
函数时,所有使用的内存都会被释放。
但是我想出了一种将 char*
表示为 String*
的新方法,但恐怕我为它保留的内存不会在以后释放。这是函数:
String* String_ToN(char* dest) {
String* temp = calloc(1, sizeof (struct String));
temp->length = strlen(dest);
temp->buffer = (char*) malloc(temp->length + 1);
strncpy(temp->buffer, dest, temp->length);
return temp;
}
我不喜欢使用 strdup
,因为它不是标准的 c,所以我会坚持使用 malloc
和 strncpy
。
这是有效的,我使用它的目的是这样的:
String_GetLength(String*)
接受一个 String*
参数,所以如果我在调用它时放入一个字符串文字,我会得到一个错误。
所以我转而使用 String_GetLength(String_ToN("hello"))
并且它像我预期的那样返回 5。
但是在 String_ToN
中我再次使用 calloc
和 malloc
,我如何释放这个内存并且仍然能够使用 ToN
?
最佳答案
与 C++ 不同,C 中没有自动资源管理(因为没有析构函数)。你必须做类似的事情:
String *hello = String_ToN("hello");
int len = String_GetLength(hello);
String_free(hello);
String_free
执行所有必要的清理工作。
关于c - 如何释放临时字符串的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8287135/