Book Image

Objective-C Memory Management Essentials

Book Image

Objective-C Memory Management Essentials

Overview of this book

Table of Contents (18 chapters)
Objective-C Memory Management Essentials
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

What's a memory leak and why pay attention to it?


A memory leak is when your program loses track of a piece of memory that was allocated and has forgotten to release it. The consequence is that the "leaked" memory will never be freed by the program. When more memory is leaked after a certain point in time, there will be no more free memory and this will cause your application to crash. Usually, this tends to happen when a piece of code does new, malloc, or alloc, but never does a corresponding "delete", "free", or "release" respectively.

When you do new, malloc, or alloc, what the operating system does is that it is giving your program a chunk of memory on the heap. The OS says, "Here, take this memory address and have this block of memory on it." Thus, you need to create a reference to that memory address (usually in the form of a pointer), depending on the OS, such as, "I'm done with this, it's not useful anymore" (by calling "free", "delete", or "release").

Memory leaks happen when you throw away your pointer to that memory. If your program does not retain where your memory is allocated on the heap, how can you even free it? The following line of code shows an example of a memory leak if you never call the release method on it:

NSMutableString *str = [[NSMutableString alloc] initWithString:@"Leaky"];

So why should you care? At best, you're the dissipating memory that will be freed when the user quits your app. At worst, there could be a memory leak that happens in every screen. It would not be a great mode to end up your program, especially if the user lets it run for a long time. A program crash is very hard to debug as it can crash at random moments in your application as memory leaks are very unpredictable to replicate and creating an application that crashes often will lead to bad reviews of your program on the App Store, or through word of mouth, which is something that you do not want to happen.

This is why in the process of evolution, there are other methods of memory management in Objective-C, which you will find further in this book.