Arpit's Newsletter read by 38000+ engineers
Weekly essays on real-world system design, distributed systems, or a deep dive into some super-clever algorithm.
Our programs need memory, typically in the form of variables and objects, to do their job. The objects are either allocated on Stack or Heap.
A locally declared variable “int a = 10;” is allocated on the stack i.e. the stack frame of the function call and hence when the function returns the stack frame is popped, making the variable non-existent. Hence variables allocated on Stack do not need to be freed explicitly.
A variable allocated on the heap is typically done through functions like the “new” or “malloc”. The object space allocated for such entities is in RAM and they outlive the function scope and execution, and hence they need to be explicitly freed as we are done with it.
Objects assigned on Heap need to be garbage collected, but why do we need the heap in the first place? There are 3 main reasons:
Primitive programming languages like C and C++ do not have their garbage collection instead expect the developer to not only allocate the object but also deallocate it explicitly. Hence we see the functions like “malloc” and “free”.
The objects we allocate using “malloc” will continue to exist unless they are reclaimed using “free”. The explicit need to “Free-ing” the allocated object is called Explicit Deallocation.
Although cleaning up the mess we created is a good idea, it is not reliable that we rely on the engineers and developers to always free the objects they allocated. Hence this gives rise to the need for automatic cleanup of unused variables- automatic garbage collection.
The two key side-effects of not cleaning up the unused objects we allocate are
Hence, to reduce human error, and make the process more reliable and performant the runtimes of the programming languages implement their automatic garbage collection.
Here's the video ⤵
Super practical courses, with a no-nonsense approach, are designed to spark engineering curiosity and help you ace your career.
An in-depth, self-paced, and on-demand course that for early engineers to become great at designing scalable, available, and extensible systems at scale.
A masterclass that helps experienced engineers become great at designing scalable, fault-tolerant, and highly available systems.
A course that helps covers Redis internals by reimplementing its core features like - event loop, serialization protocol, pipelining, eviction, and transactions.
Arpit's Newsletter read by 38000+ engineers
Weekly essays on real-world system design, distributed systems, or a deep dive into some super-clever algorithm.