Question

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.

Was it helpful?

Solution

There is no garbage collection in C!

You should read a book about C: The Definitive C Book Guide and List, specifically about pointers, the heap and the stack.

If you malloc a section of memory, the pointers live on the heap, and will not disappear or "become unusable" until free is called on that pointer. It has nothing to do with the scope of a function, which is also called a stack frame. If you declared an array of a fixed size on the stack then it would go out of scope once that stack unwinds.

In short, your last sentence is correct, if you use malloc, the memory will be allocated on the heap until you call free.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top