One common way to leak objects and their memory is to create strong references between different instances, and cut off any external references.
Let's consider the following code:
class MemoryLeak {
var ref: MemoryLeak?
init(ref: MemoryLeak) {
self.ref = ref
}
init() {
ref = self
}
}
As you can see, this is some code that you'd be unlikely to write on your own, as it doesn't have a purpose, aside from showcasing a memory leak.
The MemoryLeak class has two initializers, as follows:
- One initializer can take a reference, on to which the instance will holdĀ
- The other initializer creates a self reference
As you can imagine, this will not bode well if we use that class in code.