OwnerShip And Memory Management In Rust – 1

Rmag Breaking News

What is ownership on Rust ?

OwnerShip on rust is nothing but set of rules that decides how a rust program manages its memory ,Each programming language has its own memory management technique

Manual Memory Management – Manual memory management is utilized by programming languages like C , C++, etc.. . This gives us more control over memory , but if not handled properly it will lead to memory leak error

Automatic Memory Management – Some high-level languages, such as JavaScript, Python , utilize automatic memory management which is otherwise known as Garbage Collection GC. The purpose of a garbage collector is to monitor memory allocation and free-up the block of memory when it is no longer required

So what about rust ? and how does it handle memory ?

Rust is somewhere in between automatic and manual memory management , it uses OBRM – Ownership Based Resource Management (AKA RAII – Resource Acquisition Is Initialization)

Before diving in more let’s look at stack and heap memory

stack and heap are parts of memory that are available in your code and utilized during runtime , but both are structured different

Stack – Stack stores the values in order and it works in the concept of last in , first out .Adding data to the stack is called push and removing data to the stack is called pop. All data stored in stack should have fixed size ,and in a way stack is more organised than heap

Heap – Heap is less organised when compared to stack , when a value is stored in heap , the memory allocator finds a empty spot that is big enough and returns the pointer. Pointers are fixed size and it can be stored in stack, which can be used to get the value stored in the heap, Heap is comparatively slower than stack as the memory allocator need to search for spot each time to store a value

Rust’s ownership rules primarily concern data stored on the heap, as stack data is managed by the compiler.

Rust has certain ownership rules which has to be met before compilation

Each value in Rust has an owner.
There can only be one owner at a time.
When the owner goes out of scope, the value will be
dropped.

Additionally, Rust’s ownership rules have a few more important aspects:

1 . Values can be moved between owners, transferring ownership.
2 . After a value is moved, the previous owner can no longer access it.

If you need to share data between multiple parts of your program, you can use references (borrowing) instead of transferring ownership.

Rust’s ownership model provides the control of manual memory management while ensuring memory safety at compile-time, without the need for a traditional garbage collector. This approach makes Rust a powerful and efficient language for systems programming, concurrent programming, and other performance-critical applications.

Will continue with example’s in my next post

Leave a Reply

Your email address will not be published. Required fields are marked *