Skip to main content

Rust

Day 11: Handling Heap

Welcome back, fellow Rustacians! 🦀

In our previous article, we delved into the memory layout of an application and took a quick look at heap memory, along with some of the challenges that come with using it. Today, we’ll explore how different programming languages handle heap memory, with a focus on Python’s garbage collection and C/C++'s manual control. So, let’s get started!

Managing Heap is a critical aspect of any programming language. It involves allocating and deallocating memory dynamically during the execution of a program. Depending on their design, languages typically adopt one of two common strategies for managing heap memory: manual control, as seen in C/C++, and automatic management using a garbage collector, as done by Python.

Shallow vs Deep copy

Before we delve into the concept of a garbage collector, it’s crucial to understand how different languages create a new variable from another variable that’s allocated on the heap. For this discussion, let’s consider strings as an example.

Consider the following Python code:

# Python code
treasure_map = ["gold", "diamonds", "ruby"]
another_map = treasure_map

# Modifying another_map changes the original! (Shallow Copy)
another_map[0] = "shiny new sword"

print(treasure_map)  # Output: ["shiny new sword", "diamonds", "ruby"]

In this code, we create a list of strings called treasure_map. Then we create a new variable another_map from treasure_map. Our general expectation might be that treasure_mapand another_map are independent variables and modifying one should not affect the other. Let's run this code.