简体   繁体   English

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

[英]How to free memory from char array in C

I created a char array like so: 我创建了一个像这样的char数组:

char arr[3] = "bo";

How do I free the memory associated with array I named "arr"? 如何释放与名为“arr”的数组相关联的内存?

Local variables are automatically freed when the function ends, you don't need to free them by yourself. 当函数结束时,自动释放局部变量,您不需要自己释放它们。 You only free dynamically allocated memory (eg using malloc ) as it's allocated on the heap: 您只释放动态分配的内存(例如使用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

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;时的情况相同int n = 10; :不需要动态资源,你必须手动管理。)

The memory associated with arr is freed automatically when arr goes out of scope. arr超出范围时,与arr关联的内存将自动释放。 It is either a local variable, or allocated statically, but it is not dynamically allocated. 它既可以是局部变量,也可以是静态分配的,但不是动态分配的。

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 , calloc or realloc . 您可以遵循的一个简单规则是,您必须在调用malloccallocrealloc返回的指针上调用free()

char arr[3] = "bo";

The arr takes the memory into the stack segment. arr将内存带入堆栈段。 which will be automatically free, if arr goes out of scope. 如果arr超出范围,它将自动释放。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM