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

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.

主站蜘蛛池模板: 安丘市| 工布江达县| 沈丘县| 荥阳市| 马龙县| 丰原市| 遂平县| 独山县| 和政县| 南安市| 明光市| 长治市| 龙泉市| 巴楚县| 青铜峡市| 乌拉特中旗| 高尔夫| 大港区| 固镇县| 琼中| 洪雅县| 札达县| 行唐县| 舒兰市| 文化| 贞丰县| 韩城市| 永寿县| 手机| 甘谷县| 望城县| 滕州市| 隆尧县| 宁河县| 田东县| 梁山县| 商都县| 东乡| 白玉县| 都兰县| 安龙县|