+ 7
It's not the code that is deallocated, it is the memory used by functions and objects.
Stack based memory deallocation is automatic so no action was required from the coder. Heap based memory on the other hand, is not automatically deallocated, so manual memory deallocation is necessary.
Why heap memory deallocation is important? because we take responsible for cleaning up the room once we're done playing with toys. Leaving garbage and toys lying around after playing may be considered an act of carelessness and irresponsibility.
+ 3
HungryTradie, your questions are not so easily answered in all generality, I'm afraid.
One thing can be said for certain: even here on Sololearn you should always deallocate any memory you requested from the heap. Why? Because it trains conscious use of memory. Thinking it doesn't matter here will have you forget about it in situations where you have to - simply because you have adopted this sloppiness.
As a rule of thumb, memory should be freed as soon as the resource that owns it goes out of scope. There may be exceptions to this rule.
Reallocating dynamically sized objects is often done doubling its capacity. The purpose behind it is that insertion is O(1) on a direct access structure (e.g. array). Reallocation may require a copying of already stored elements, an O(N) operation, N being the capacity. Doubling the capacity still provides an O(1) armortised time complexity. Each insertion is a bit more expensive but still independent of the capacity.
+ 1
Great question Manav Roy , and thanks Ipang for the answer.
Would you go a bit further with your explanation, when should we free the heap? I think that here in SoloLearn it is not really necessary because the programs are simple and the environment is limited.
My question: When we are coding an interactive program with a repeating code, should we free the heap on each iteration?
Eg: looping back to the start again, should I free before the repeat, and then calloc again when the size of the data is known, realloc if it increases? Or should I just go straight to realloc to shrink the heap allocation back to minimum at the start?
+ 1
Thanks Ani Jona đ
I might try to do some realloc of a pointer array in SoloLearn code bits to see how it goes. I will start with memory for 4 char, but then add more as I build a sentence. I think I'll use a loop with a realloc somewhere. I'll let you know if I get it to work đ
Also, great suggestion about training to free after malloc/calloc. It can be for me like remembering to close a curly brace, or remembering to return at the end of a function. When I add calloc I will add free just above the return, then fill in the middle. đ
+ 1
Here goes! Uncomment the realloc to get it to work đšđđ
https://code.sololearn.com/c24uafGqxgo5/?ref=app