Memory management is a fundamental concern in any programming language.
In this article we look at how rust manages the heap allocated data and how it differs with respect to other languages like c++ and python
Welcome back, fellow Rustaceans 🦀
In the last article, we learned about our first heap-allocated data structure in Rust, the String. In today's article, we'll circle back to our discussion on how different languages manage heap-allocated structures and learn how Rust approaches this issue.
On Day 10, we learned how Python uses a garbage collector to manage heap-allocated structures based on reference counting. Even though it's a great solution to manage heap memory, it comes with runtime costs and memory overhead required by the garbage collector. This may not fit the realm of systems/embedded engineers, where we need precise control of memory and are usually resource-constrained. On the contrary, C allows total control of heap memory to users by using malloc and free. This comes with its own set of problems like dangling pointers, double frees, and has been the source of countless security vulnerabilities.
So, what is it that Rust does that makes it so different? Well, let's have a look at the below C++ code from day 10:
In the above code, we create a vector of strings treasure_map, with all elements allocated on the heap. Then, we create another variable named another_map and initialize it using treasure_map. C++ does a deep copy here, creating two independent copies of the data structure. This makes sense, as unlike Python, there is no garbage collector to track reference counts. If you want a shallow copy, you would need to track both treasure_map and another_map usage throughout the code, as modifying one will impact the other. Even worse, you have to make sure that both references are invalidated at the same time. Invalidating one while still using the other will lead to segmentation faults.
Over the decades, many tools, bureaucracy, and review processes have been deployed to avoid such kinds of issues. However, memory issues are still the most common vulnerability in C/C++ codebases. In 2019, Microsoft security researchers presented that 70% of all vulnerabilities in Microsoft codebases are a result of memory vulnerabilities.
Don't Miss an Update!
Helping you navigate the Embedded Systems career with ease! Technical posts, newsletters, special offers, and more.