如何释放 C 中作为函数参数传递的字符数组
我遇到了一个问题,我不确定这是否是一个问题。我有一个简单的 C 函数,它获取从字符串传递的 char* ,如下所示:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
passString("hello");
return (EXIT_SUCCESS);
}
void passString(char * string) {
// .... some code ....
free(string); // ???
}
我被教导释放我不再使用的每个内存块(主要是数组)。所以我的想法是也释放字符串,但即使使用这个简单的示例,程序也会冻结或崩溃。我不确定我是否真的需要在这里释放字符串,如果是的话我该如何实现呢?
I came across an issue that I am not sure if it's an issue at all. I have a simple C funcion that gets a char* passed from string like so:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
passString("hello");
return (EXIT_SUCCESS);
}
void passString(char * string) {
// .... some code ....
free(string); // ???
}
and I was taught to free every memory block that I'm not working with anymore (mainly arrays). So my though was to free string as well but the program freezes or crashes even with this simple example. I'm not sure whether I really need to free string here or not and if so how do I achieve that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不需要
释放
未使用malloc
分配的内存。在您的示例中,
string
不是由程序中的malloc
分配的,因此您不需要释放它。string
是一个字符串文字,被分配在只读内存中的某个位置(实现定义)并自动释放。对于标准粉丝:
参考文献:
c99 标准:7.20.3.2
免费
功能You do not need to
free
memory which you did not allocate withmalloc
.In your example
string
is not allocated bymalloc
in your program so you do not need to free it.string
is a string literal and is allocated somewhere in the read-only memory(implementation defined) and is automatically freed.For standerdese fans:
References:
c99 Standard: 7.20.3.2 The
free
function如果您愿意的话,您要释放的字符串是静态分配的,“在编译期间”。事实上,任何字符串文字(
"hello"
)都是这样完成的。您无法释放静态分配的内存,因为它不存在于堆中。作为一般规则,实际上最好在分配时释放。在这种情况下,如果您要为
"hello"
动态分配空间,您将执行以下操作:The string you're freeing is statically allocated, "during compilation" if you will. Indeed any string literal (
"hello"
) is done this way. You cannot free statically allocated memory as it does not live in the heap.As a general rule, it's actually better to free at the point of allocation. In this case, were you to dynamically allocate space for
"hello"
, you would do this:您只需要释放动态分配的内容(通过 C 中的 malloc 或通过 C++ 中的关键字 new)。基本上,对于像
malloc()
这样的任何分配调用,都应该在某个地方有一个free()
。字符串文字不是动态分配的,您不需要关心它们。
You only need to free what you've allocated dynamically (via malloc in C or via keyword new in C++). Basically, for any allocation call like
malloc()
there should be afree()
somewhere.String literals aren't dynamically allocated and you don't need to be concerned about them.