C语言 如何从C中的char数组中释放内存

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21513666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 10:43:26  来源:igfitidea点击:

How to free memory from char array in C

c

提问by AbhishekSaha

I created a char array like so:

我创建了一个像这样的字符数组:

char arr[3] = "bo";

How do I free the memory associated with array I named "arr"?

如何释放与我命名为“arr”的数组关联的内存?

回答by rullof

Local variables are automatically freed when the function ends, you don't need to free them by yourself. You only free dynamically allocated memory (e.g using malloc) as it's allocated on the heap:

局部变量会在函数结束时自动释放,无需您自行释放。您只能释放动态分配的内存(例如 using malloc),因为它是在堆上分配的:

char *arr = malloc(3 * sizeof(char));
strcpy(arr, "bo");
// ...
free(arr);

More about dynamic memory allocation: http://en.wikipedia.org/wiki/C_dynamic_memory_allocation

更多关于动态内存分配:http: //en.wikipedia.org/wiki/C_dynamic_memory_allocation

回答by Kerrek SB

You don't free anything at all. Since you never acquired any resources dynamically, there is nothing you have to, or even are allowed to, free.

你根本没有释放任何东西。由于您从未动态获取任何资源,因此您无需或什至不允许免费获得任何资源。

(It's the same as when you say int n = 10;: There are no dynamic resources involved that you have to manage manually.)

(这与您所说的相同int n = 10;:不涉及您必须手动管理的动态资源。)

回答by David Heffernan

The memory associated with arris freed automatically when arrgoes out of scope. It is either a local variable, or allocated statically, but it is not dynamically allocated.

超出范围arrarr会自动释放与之关联的内存。它要么是局部变量,要么是静态分配的,但不是动态分配的。

A simple rule for you to follow is that you must only every call free()on a pointer that was returned by a call to malloc, callocor realloc.

您要遵循的一个简单规则是,您必须只free()对由对malloccalloc或的调用返回的指针进行每次调用realloc

回答by Ramkumar lodhi

char arr[3] = "bo";

The arr takes the memory into the stack segment. which will be automatically free, if arr goes out of scope.

arr 将内存带入堆栈段。如果 arr 超出范围,它将自动免费。