0

I need to code a function in which i declare a new array and then i need that array to stay in the memory...

I was wondering which is the best programming practice to attain this result, and i would also love to understand how does the garbage collector work in this specific situation

More in the case, if i declare a function and inside it i inizializate an array, if i keep the reference to the address outside the function, Once the function as finished working, and it's enviroment cease to exist, will the Array still be usable, or do i risk that further malloc or array declaration would unexpectdly override my previuos array?

also, if i use a malloc inside a function, will the memory allocated stay reserved untill i free it no matter where i do use the malloc?

Thanks for the help anyone will offer.

4

1 回答 1

1

C中没有垃圾收集!

你应该读一本关于 C: The Definitive C Book Guide and List 的书,特别是关于指针、堆和堆栈的书。

如果您malloc是一段内存,则指针位于堆上,并且在对该指针调用 free 之前不会消失或“变得不可用”。它与函数的作用域无关,也称为栈帧。如果您在堆栈上声明了一个固定大小的数组,那么一旦堆栈展开,它将超出范围。

总之,你最后一句话是对的,如果你使用malloc,内存会在堆上分配,直到你调用free。

于 2013-05-24T14:54:29.233 回答