How a program looks like in RAM?
When a compiled/executable program gets loaded in memory it becomes a process and operating systems manages all relevent process information like process id, process state etc. into the Process Control Block(PCB). A typical process in memory is divided into the following major segments
Code/Text Segment
Contains the compiled executable machine code.
This is read only section to prevent accidental modification.
This section can be shared with the other instances of the same program for saving resource.
Data Section
This section stores the all static and global variables.
It’s a read-write section.
It's further divided into:
Initialized data (variables with explicit initial values)
Uninitialized data (BSS) (variables that are zero-initialized by default)
Stack
This is the section where all local variable and function parameter return address on function get stored.
It operates in Last in First out manner it grows towards the lower memory address.
Managed automatically by runtime.
Heap
This is used for dynamic memory allocation(object which size is not known at compile time get stored here like vector, string, map etc.)
Grows upward towards the higher memory address.
It is managed by programmer in C, CPP and by runtime in Go and JAVA.
Our most of the discussion will be around the heap memory because most of the problem comes in heap.
How memory get allocated & deallocated?
In C, when we write malloc() it allocates memory in heap and when we use free(), then frees the memory.
In Java or Go just use the make() or new and do not care about the either memory allocation or deallocation, runtime and Garbage collector(CG) take care about the memory allocation and deallocation. but it comes with some cost.
And then Rust came in the picture with the complete new memory model which enforces deterministic deallocation via ownership, borrowing and lifetime whenever the scope of the function over then memory allocated in heap also get deallocated without involving GC.
we can say that now we have three types of programming language First in which programmer has to allocate and deallocate the heap memory. Second one is which allocation will taken care by runtime and deallocation will be taken care by GC. Third one in which allocation will taken care by runtime but heap memory is freed automatically and deterministically when the owner goes out of scope so no manual or no GC.


