The Rust Programming Language
The Rust Programming Language

The Rust Programming Language — Ownership — Memory Management of Rust

Why Rust stands out in memory management!

Ankit Tanna
Published in
11 min readOct 21, 2023

--

Rust, unlike C and C++, has an automatic memory management system. It revolves around 3 main concepts in Rust:

  1. Ownership
  2. Borrowing
  3. Lifetimes

You must have come across malloc,calloc and realloc in C/C++. These methods were for memory allocation and deallocation during the lifecycle of the program. They had to be called manually.

In this article, we’ll learn about manual memory management and and automatic memory management and then about ownership. Pre-requisite of this article is to understand how stack and heap memory works. We know that how a vector full of numbers is going to be stored on a heap memory.

We are aware of the fact that when a function returns a vector, it stores the metadata of the vector in the stack memory and it stores the actual elements of the vector in the heap memory.

Let’s talk about the Heap’s memory management system. Whenever we call a vec![] macro like below:

let nums = vec![1, 2, 3];

Rust actuall calls alloc(3) internally to allocate 3 places in the heap memory for 1, 2 and 3 numbers of the vector. It…

--

--