Summary of basic principles of iOS

In iOS, memory is mainly divided into stack area, heap area, global area, constant area, code area five areas. As shown in the figure below

Here are the five regions

Stack area

define

  • The stack isSystem data structureAnd its correspondingA process or thread is uniquethe
  • The stack isScale to a lower addressData structure of
  • Is a piece of the stackContiguous memory areas, follow theFirst in last Out (FILO)The principle of
  • Of the stackAddress spaceIn iOS it is0 x7 beginning
  • The stack area is generally inRuntime allocation

storage

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

  • A local variable
  • Parameters of a function, such as the function’s hidden argument (id self, SEL _cmd)

The advantages and disadvantages

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

  • Disadvantages: limited stack memory size, inflexible data

    • The iOS main thread stack size is 1MB
    • The other threads are512KB
    • MAConly8M

The above instructions for memory size are provided in the Threading Programming Guide

Heap area

define

  • The heap isExtend to higher addressesData structure of
  • The heap isA discontinuous memory region, similar to theChain table structure(easy to add and delete, not easy to query), followFirst in first out(FIFO) principle
  • The heapAddress spaceIn iOS it is0x6At first, the allocation of space is always dynamic
  • The allocation of heap areas is generally inRuntime allocation

storage

The heap area is allocated and released dynamically by the programmer. If the programmer does not release it, it may be reclaimed by the operating system after the program is finished, mainly for storage

  • OCThe use ofallocOr usenewOpen up space to create objects
  • CLanguage useMalloc, Calloc, ReallocAllocated space, neededfreeThe release of

The advantages and disadvantages

  • Advantages: flexible and convenient, wide range of data adaptation
  • Weakness: the need toManual management.Slow speedAnd easy toGenerate memory fragmentation

When accessing memory in the heap, it is generally necessary to read the pointer address of the stack through the object, and then access the heap through the pointer address

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

The global area is the memory space allocated at compile time, which generally starts with 0x1 in iOS. During the program running, the data in this memory is always stored and released by the system after the program ends

  • uninitializedtheThe global variableandA static variable, that is, BSS region (.bSS)
  • initializedtheThe global variableandA static variableData area (.data)

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

Constant area (.rodata)

The constant area is the memory space allocated at compile time and released by the system at the end of the program

  • Already used and not directed toString constant

Because string constants can be used more than once in a program, memory is allocated before the program runs

Code area (.text)

Code areas are allocated at compile time to store code that is compiled into binary and stored in memory while the program is running

Five areas of memory validation

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(@"obj memory address: %p", obj); NSLog(@"&obj memory address: %p", &obj); }Copy the code

The result is as follows

The results

  • For the local variable I, the address begins with 0x7, so I is stored on the stack

  • For the string object string, we print the address of the string object and the address of the pointer to the string object

    • A string ofAddress of the objectBased on0 x1 beginning, indicating that it is storedThe constant area
    • stringObject pointer addressBased on0 x7 beginning, indicating that it is storedThe stack area
  • For the object obj created by alloc, the object address of OBj and the pointer address of obj are printed respectively (see the summary diagram above).

    • The objAddress of the objectBased on0 x6 beginning, indicating that it is storedThe heap area
    • objObject pointer addressBased on0 x7 beginning, indicating that it is storedThe stack area

The function of stack

  • The function of stackAlso known as theThe stack areaTo allocate memory from the highest address to the lowest address, as opposed to the heap. See the illustration at the beginning of this article
  • The stack frameRefers to theA separate contiguous area of memory occupied by a function (running and incomplete)
  • Newly created in the applicationEach thread has its own stack spaceThe stack can be used freely during the thread. And there are tens of thousands of function calls in the thread, these functionsSharedThis of the processStack space.The stack space used by each function is one stack frame, and all the stack frames make up the complete stack of the thread
  • Function calls occur on the stackThat eachInformation about the function(for example, local variables, call records, etc.)Store in a stack frameRun the command onceA function call, generates a stack frame associated with it, and then converts itThe stack frame is pushed onto the function stackAnd when the delta functionPerform the end, then the corresponding of this functionThe stack frame goes off the stack and is released

As shown in the figure below, it is the stack frame layout of classic Graph-ARM

  • Among themmain stack frameforCall the stack frame of the function
  • func1 stack frameforThe stack frame of the current function (called)
  • The bottom of the stackinhighAddress, stack goes down.
  • FPisThe stack baseIt points to the delta functionStart address of stack frame
  • SPIt’s a functionThe stack pointer, it points toTo the top of the stackThe location of the.
  • ARM pressure stacktheThe orderVery regular (and relatively easy to hack), in orderCurrent function pointer PC,Return pointer LR,The stack pointer SP,The stack base FP,Number of arguments and Pointers passed in,The local variableandTemporary variable. If a function is about to call another function, the temporary variable area should hold the other function’s arguments before jumping.
  • The ARM can alsoUse the stack base address and the stack pointer to indicate the position of the stack frame, the stack pointer SP keeps moving, ARM’sThe characteristics ofIs that,The address in both stack Spaces (SP+FP) must be preceded by two code addresses (PC+LR) that explicitly identify an address within the location of the calling function.

Stack overflow

In general, applications do not need to consider the size of the heap and stack, but the reality is that the heap and stack are not unlimited. Too much recursion can cause stack overflows, and too many alloc variables can cause heap overflows.

So ways to prevent stack overflow: (1) avoid deep recursive calls;

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

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

(4) If it is not possible, call system API to modify the stack size of thread in appropriate situation;

The stack frame sample

Describes the stack frame variation of the following code

Stack frame program example

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 stack frame in stack area during program execution is shown in the figure below