mainmatter / 100-exercises-to-learn-rust

A self-paced course to learn Rust, one exercise at a time.
https://rust-exercises.com
4.99k stars 861 forks source link

03_ticket_v1 /09_heap.md No Automatic De-allocation #155

Closed unpeturbed closed 1 week ago

unpeturbed commented 1 week ago

While reading this repo/book, I came across a statement regarding memory management in Rust that reads:

"It's the allocator's job to keep track of which parts of the heap are in use and which are free. The allocator won't automatically free the memory you allocated, though: you need to be deliberate about it, calling the allocator again to free the memory you no longer need."

I would like to clarify the following points:

  1. Automatic Memory Management: While Rust uses a system of ownership with a built-in garbage collectior, the statement implies manual memory management like we have in C. Can you clarify how Rust's ownership and borrowing rules interact with memory allocation and deallocation?

  2. Allocator Behavior: How does Rust's allocator handle memory management when an object goes out of scope? Does Rust automatically free memory in these cases, or is manual intervention required?

I am new to Rust and am trying to understand its approach to memory management. The statement highlighted seems to contradict what I had read in the Rust Book. Any insights or clarifications from the community would be greatly appreciated.

Thank you muchos

c-git commented 1 week ago
1. **Automatic Memory Management**: While Rust uses a system of ownership with a built-in garbage collectior, the statement implies manual memory management like we have in C. Can you clarify how Rust's ownership and borrowing rules interact with memory allocation and deallocation?

So rust doesn't use a garbage collector. What it does is based on the ownership rules it does the manual memory management for you based on when owned values get dropped. Values get dropped when they go out of scope because then based on the ownership rules they cannot be referenced from anywhere else and it's safe to drop them. When they are dropped the call to free is automatically included in the compiled code without you needing to remember to do it.

2. **Allocator Behavior**: How does Rust's allocator handle memory management when an object goes out of scope? Does Rust automatically free memory in these cases, or is manual intervention required?

Yes rust will compile in the call to free for you and no manual intervention is required.

unpeturbed commented 1 week ago

Got you. Was a bit confused when I saw that statement. Thank you for the clarification.

c-git commented 1 week ago

No worries glad I could help. If that resolves your issue feel free to close this issue.