官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 随州市| 宽城| 安龙县| 合水县| 贵阳市| 阿勒泰市| 呼图壁县| 浦东新区| 湖口县| 界首市| 福清市| 太康县| 鄂托克前旗| 商城县| 正蓝旗| 英吉沙县| 云龙县| 济宁市| 安福县| 汉阴县| 神木县| 宜昌市| 梓潼县| 井陉县| 华坪县| 绥芬河市| 庄浪县| 新巴尔虎左旗| 阿图什市| 嫩江县| 麻江县| 介休市| 普宁市| 共和县| 丽江市| 津南区| 兴化市| 白水县| 东城区| 嘉荫县| 宁海县|