IOS underlying principles + reverse article summary

In iOS, memory is divided intoStack, heap area, global area, constant area, code areaFive regions. See the figure below

Here are the five regions

Stack

define

  • A stack is a system data structure whose corresponding process or thread is unique

  • A stack is a data structure that extends to a lower address

  • A stack is a continuous area of memory that follows the first in, last out (FILO) principle

  • The stack address space starts with 0X7 in iOS

  • Stacks are typically allocated at run time

storage

The stack area is automatically allocated and freed by the compiler and is mainly used for storage

  • A local variable

  • Function arguments, such as hidden arguments to the function (id self, SEL _cmd)

The advantages and disadvantages

  • Advantages: Because the stack is automatically allocated and freed by the compiler, no memory fragmentation is generated, so it is fast and efficient

  • Disadvantages: Memory size of stack is limited, data is not flexible

    • IOS main thread stack size is 1MB

    • Other threads are 512KB

    • MAC only 8 m

The above memory sizes are described inThreading Programming GuideThere are related instructions in

Heap area

define

  • A heap is a data structure that extends to a higher address

  • The heap is a discontinuous area of memory, similar to a linked list structure (easy to add and delete, not easy to query), and follows the first-in, first-out (FIFO) principle

  • The address space of the heap starts with 0x6 in iOS and is always allocated dynamically

  • The allocation of the heap is typically made at run time

storage

Heap area is dynamically allocated and released by the programmer, if the programmer does not release, after the end of the program, may be recycled by the operating system, mainly used for storage

  • OC creates objects using alloc or new space

  • The space allocated by malloc, calloc, and realloc in the C language needs to be free

The advantages and disadvantages

  • Advantages: Flexible and convenient, wide range of data adaptation

  • Disadvantages: Requires manual management, slow speed, easy to generate memory fragmentation

When you need to access the memory in the heap, you usually need to read the pointer address of the stack area through the object, and then access the heap area through the pointer address

Global extents (static extents, i.e..bss &.data)

The global area is the memory space allocated during compilation. In iOS, it usually starts with 0x1. During the program running, the data in the memory always exists, and is mainly stored by the system after the program ends

  • Uninitialized global and static variables, i.e. BSS area (.bSS)

  • Initialized global and static variables, the data area (.data)

A global variable is a variable whose value can be dynamically modified at run time, while a static variable is a static variable that contains both a static local variable and a static global variable

Constant area (i.e..rodata)

Constant area is the memory space allocated at compile time, released by the system after the end of the program, mainly stored

  • Already used and not pointed toString constant

Because string constants can be used multiple times in a program, memory is allocated before the program runs

Code area (i.e..text)

The code area is allocated at compile time to store code that will be compiled into binary and stored in memory

Memory five area verification

Run the following code to see how variables are allocated in memory

- (void)test{ NSInteger i = 123; NSLog(@" I memory address: %p", &i); NSString *string = @"CJL"; NSLog(@" memory address of string: %p", string); NSLog(@"&string memory address: %p", &string); NSObject *obj = [[NSObject alloc] init]; NSLog(@" %p", obj); NSLog(@"&obj memory address: %p", &obj); }Copy the code

The result is as follows

  • forLocal variable I, as you can see from the address0 x7 beginningSo I is storedThe stack area
  • forString object string, respectivelyThe object address of stringThe address of a pointer to a string
    • The object address of string starts with 0x1, indicating that it is stored in the constant area

    • The address of a pointer to a string starts with 0x7, indicating that it is stored on the stack

  • forAlloc creates object obj, respectivelyObj Specifies the object addressObj Indicates the address of a pointer to an object(Refer to the summary above)
    • The object address of obj starts with 0x6, indicating that it is stored in the heap

    • The address of the pointer to the obj object starts with 0x7, indicating that it is stored in the stack

The function of stack

  • Function stacks, also known as stack areas, are allocated from high to low addresses in memory, as opposed to the heap area. See the diagram at the beginning of this article for details

  • A stack frame is a separate contiguative area of memory occupied by a function that is running and not completed

  • Each new thread created in the application has a dedicated stack space, and the stack can be used freely during the duration of the thread. There are thousands of function calls in the thread, and these functions share the stack space of the process. The stack space used by each function is a stack frame, and all the stack frames make up the entire stack of the thread

  • Function call is on the stack, and each function of the relevant information (such as local variables, call records, etc.) are stored in a stack frame, each performs a function call, it will generate a stack frame associated with them, and then press the stack frame into function stack, and when the end of the function, this function corresponding frame out of the stack and released

As shown in the following figure, is the classic diagram –ARM stack frame layout

  • The main stack frame is the stack frame of the calling function

  • Func1 stack frame is the stack frame of the current function (called)

  • The bottom of the stack is at the high address, and the stack grows downward.

  • FP is the stack base address, which refers to the start address of the stack frame of the function

  • SP is the stack pointer to the function, which points to the top of the stack.

  • The order of ARM stack pressing is very regular (also relatively easy to be hacked), the order is the current function pointer PC, return pointer LR, stack pointer SP, stack base address FP, the number of parameters passed and pointer, local variables and temporary variables. If a function is about to call another function, the temporary variable area holds the parameters of the other function before jumping.

  • ARM can also use the stack base address and the stack pointer to clearly mark the position of the stack frame, the stack pointer SP has been moving, ARM is characterized by two stack space address (SP+FP), there must be two code address (PC+LR) clearly marked an address in the calling function position.

Stack overflow

In general, applications do not need to consider the size of heap and stack, but in fact heap and stack are not unlimited, too much recursion will lead to stack overflow, too many alloc variables will lead to heap overflow.

Therefore, the methods to prevent stack overflow are as follows: (1) to avoid recursive calls that are too deep;

(2) Do not use too many local variables, control the size of local variables;

(3) Avoid allocating objects that occupy too much space and release them in time;

(4) In case of failure, call the system API to modify the thread stack size;

The stack frame sample

Describe the stack frame changes in the following code

Example stack frame program

int Add(int x,int y) {
    int z = 0;
    z = x + y;
    return z;
}

int main() {
    int a = 10;
    int b = 20;
    int ret = Add(a, b);
}
Copy the code

The change of the stack frame in the stack area when the program is executed is shown in the figure below