SHH, don’t talk. Kiss me.

A, cause

Let’s start with a piece of code

Results:

Three different Pointers (addresses 8 bytes apart) point to the same memory region

Note :%@-obj1 prints the type and memory address of the object

%p-obj1 Prints the memory address of the object

%p-&obj1 Prints a pointer to an object

Question:

1. What does alloc do?

2. What does init do?

3. How to read the source code of these functions?

Two or three ways to break (let the source surface)

1. Symbolic breakpoints

First add a breakpoint to the alloc function

②, Then hold down control and click step into button (can be clicked multiple times)

The breakpoint is now here (see objc_alloc).

Add a sign breakpoint to objc_alloc

Libobjc.a.dylib = _objc_rootAllocWithZone

2. Assembly

First add a breakpoint to the alloc function

2. Select Debug -debug Workflok -always Show Disassembly

③ While going to objc_alloc, hold down control and click step into to go to the objc_alloc function, and then sign breakpoint (same way).

3. Known symbolic breakpoints

Direct sign breakpoint alloc

At this point, you know where the source code is, so go to the Apple website to download openSource.apple.com

Configured source github.com/wangshaofen…

Third, edit the source code, you can view the alloc process

1. Compiler optimization

2. InstanceSize

And then we go into calculation mode

Eg: (x + WORD_MASK) & ~WORD_MASK (8+7)&(~7) 15: 0000 1111 7: 0000 0111 ~7: 1111 1000 15&(~7): 0000 1000 = 8 or 8 byte alignment

As you can see from the code, Apple internally calculates memory with 8-byte alignment and allocates memory with 16-byte alignment