Memory allocation (heap and stack) in iOS development

Source: Internet
Author: User

memory partition of the process

All processes (executing programs) must occupy a certain amount of memory, either to store program code loaded from disk, or to store data from user input, and so on. However, the way the process manages these memory is different from memory usage, some of which are statically allocated and collected uniformly, while others are dynamically allocated and reclaimed as needed.


Process memory area. png
    1. Code Area: A code snippet is an action instruction that holds an executable file (the binary code that holds the function), that is, it is a mirror of the stored species that executes the program. Code snippets need to be prevented from being illegally modified at run time, so only read operations are allowed, not write (modify) operations--it is not writable.

    2. The Global (static) zone consists of the following two partitions:

      • Data area: Data segments are used to store initialized global variables in an executable file, in other words, variables and global variables that are statically allocated by the program.

      • BSS: BSS section contains uninitialized global variables in the program.

    3. constant Area: constant storage, which is a special storage area, they are stored in constant,

    4. Heap Zone: a heap is allocated and freed by programmers to hold dynamically allocated memory segments in a process run, which is not fixed in size and can be dynamically expanded or scaled down. When the process calls Alloc and other functions to allocate memory, the newly allocated memory is dynamically added to the heap (the heap is expanded), and when the memory is freed with Realse, the freed memory is removed from the heap (heap is reduced) because we now basically use ARC to manage the object, so we don't need our programmers to manage , but we need to know where this object is stored.

    5. Stack zone: stacks are automatically assigned and freed by the compiler , local variables that are temporarily created by the user-stored program, stored function parameter values, local variables, and so on. That is, we function the variables defined in parentheses "{}" (but do not include the static declared variables, which means that the variables are stored in the data segment). In addition, when a function is called, its arguments are pressed into the process stack where the call is initiated, and the return value of the function is returned to the stack when the call is finished. Due to the advanced first-out features of the stack, the stack is particularly handy for saving/recovering call sites. In this sense we can think of the stack as a temporary data storage, swap memory area.

The data segments, BSS, and heap in the above-mentioned memory areas are often stored continuously-memory locations are contiguous, and code snippets and stacks are often stored independently.

A stack is a data structure that extends to a low address and is a contiguous area of memory. A heap is a data structure that extends to a high address and is a discontinuous area of memory. Some people will ask whether the heap and the stack will come together, they are spaced very large, there is little chance to meet together, and the heap is the list of the way to store!

#import"ViewController.h"int age =24;Global initialization zone (data area)NSString *name;Global uninitialized Zone (BSS zone)StaticNSString *sname =@ "dely";Global (static initialization) zone@implementationviewcontroller-(void) Viewdidload {[Super Viewdidload];int tmpage;StackNSString *tmpname =@ "dely"; //stack nsstring *number = @ "123456"; //123456\0 in the constant area, number on the stack. nsmutablearray *array = [nsmutablearray arrayWithCapacity: 1]; //the allocated 8-byte area is in the heap, array in the stack, point to the address of the heap area nsinteger total = [self gettotalnumber:1 number2:1];} -(nsinteger) Gettotalnumber: (nsinteger) number1 number2: ( nsinteger) number2{return number1 + number2;//number1 and number2 stack area} @end       
Heap and stack (stack) differences
  1. How to apply and how to recycle

    • Stack: Automatically allocated and freed by the compiler
    • Heap area: Allocated and freed by programmers
  2. Response of the system after application

    • Stack: Store each function in the execution of the operating system to ask for resources, the stack is the function of the memory, the stack is responsible for the allocation of variables in the repository and release, memory with the function of the allocation, with the function of the end of the release, the system automatically completed. As long as the remaining space of the stack is larger than the requested space, the system will provide memory for the program, otherwise it will report the exception prompt stack overflow.

    • Heap: The operating system has a list of idle memory addresses, and when the system receives the application of the program, it iterates through the list, finds the heap node where the first space is larger than the requested space, and then removes the node from the list of idle nodes and assigns the space of that node to the program, in addition, for most systems, The size of this allocation is recorded at the first address in this memory space, so that the DELETE statement in the code can properly free up the memory space. Also, because the size of the found heap node does not necessarily equal the size of the request, the system automatically re-places the extra portion into the idle list.

  3. Limit for size of application

    • Stack: A stack is a data structure that extends to a low address and is a contiguous area of memory. This sentence means that the top of the stack of the address and the maximum capacity of the stack is the system pre-defined, the size of the stack is 2M (also may be 1M, I see on-line, I do not know), if the application of space beyond the stack of the remaining space, will prompt stack overflow. Therefore, the space available from the stack is small.

    • Heap area (stack): A heap is a data structure that extends to a high address and is a discontinuous area of memory. This is because the system is stored with a linked list of free memory address, is naturally discontinuous, and the chain of the list of traversal direction is from the low address to high address. The size of the heap is limited by the valid virtual memory in the computer system. Thus, the space of the heap is more flexible and relatively large.

  4. Comparison of application efficiency

    • Stack: Automatically allocated by the system, faster. But programmers can't control it.

    • Heap area (Stack): Is the memory allocated by the ALLOC, the general speed is relatively slow, and easy to produce memory fragmentation, but the most convenient to use.

  5. Comparison of distribution methods

    • Stack: There are 2 ways to allocate: Static allocation and dynamic allocation. Static allocations are done by the compiler, such as the allocation of local variables. The dynamic allocation is assigned by the Alloc function, but the dynamic allocation of the stack is different from the heap, and his dynamic allocation is released by the compiler without our manual implementation.
    • Heap area (stack): The heap is dynamically allocated and there are no statically allocated heaps.
  6. Comparison of allocation efficiency

    • Stack: Stack is the data structure provided by the operating system, the computer will support the stack at the bottom: assigning the address of a dedicated register storage stack, the stack stack has a special command execution, which determines the efficiency of the stack is high.
    • Heap area (stack): The heap is provided by the C + + function library, its mechanism is very complex, for example, in order to allocate a piece of memory, the library function will follow a certain algorithm (the specific algorithm can refer to the data structure/operating system) in the heap memory to search for a sufficient amount of space available, If there is not enough space (possibly due to too much memory fragmentation), it is possible to call the system function to increase the memory space of the program data segment, so that there is a chance to get enough memory and then return. Obviously, the heap is much less efficient than the stack.

Summary:
Use stacks like we go to buy a cake, money and then choose a taste, a shape of cake to get, no matter how they do, how to design, this benefit is fast, pay to buy services (I am not good, a bit dirty), but the degree of freedom is very small.

Using the heap like we go to buy a handmade cake, because there is friendship ah DIY, do like to eat their own shape, and their favorite taste, more trouble, but more in line with their own tastes, and the freedom is large.

Today's Ox x is blown here, in the middle of what error please put forward to mercilessly interrogates me, thank you for your visit!

Resources:
http://blog.csdn.net/liruxing1715/article/details/6715503



Wen/dely (author of Jane's book)
Original link: http://www.jianshu.com/p/746c747e7e00
Copyright belongs to the author, please contact the author to obtain authorization, and Mark "book author".

Memory allocation (heap and stack) in iOS development

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.