Local variable is allocated in stack,
a temporal storage of function.
If you return a reference of local variable,
the address will be invalidated.
If these two functions are far away from each other,
this kind of bugs can be very hard to find.
Can you see the problem?
Even a famous library
may betray you
If you do not know much
about the internals...
• Java, Python, Ruby, C#, Scala, Go...
• Programmer creates objects. However,
the computer is responsible to remove
• No explicit malloc and free.
– Therefore no mistake.
Is the world saved?
The real life is not that easy...
• Computer cannot know the exact timing
that each object should be freed.
– tracing GC:GC engine should track all objects
– reference counting: every object has a
counter; the number of pointers referencing
• Both ways need more memory and CPU
• No predictability
– cannot used for real-time system
• Limited concurrency
– global interpreter lock
• Larger code size
– VM(or GC) must included
• Must be FAST.
• Must has runtime overhead as little as
• Must be memory SAFE.
• Should be possible to direct memory
• GC cannot be used in such area!
Rust programming language
• Zero-cost abstraction
• Memory safety without garbage collection
• Super fast code generation
• C function compatibility (extern "C")
• Simpler syntax than C++
Case study: Servo
• Mozilla's next-gen web browser engine
• Written in Rust
• Parallel layout, rendering, ... almost
• "During the 2 years of development, we
have never experienced any memory-
related bugs like use-after-free or double
- an engineer from Mozilla
• You cannot borrow mutable reference from immutable
• You can borrow immutable reference many times
• You cannot borrow more than one mutable reference
• There cannot exist a mutable reference and an
immutable one simultaneously
• The lifetime of a borrowed reference should be ended
before the owner object do