Why does the message sending program to nil in Objective-C not crash?

Source: Internet
Author: User

We know that the message sending program to nil in Objective-C will not crash,

Objective-C is based on the C language,

On PC, null pointer operations are performed in C language,

The program crashes due to a protection error due to out-of-bounds access,

But why won't Objective-C crash?

The reason must be found in the source code,

The following is the arm assembly code snippet of objc_msgSend:

In the arm function call process,

Generally, parameters are transmitted by r0-r4,

Use r0 to pass the returned value.

Corresponding to objc_msgSend. The first parameter is self, and the returned value is self, which is put in r0 (a1.

 

 

/*************************************** *****************************

* Idobjc_msgSend (idself, SELop ,...)

* On entry:A1 is the message sender er,

*A2 is the selector

**************************************** ****************************/

 

ENTRY objc_msgSend

# Check whether receiver is nil

Teq a1, #0

Moveq a2, #0

Bxeq lr

 

Teq instructions:

TEQ Rn,Operand2 The TEQ instruction performs a bitwise Exclusive OR operation on the value in Rn and the value of Operand2.

Test whether self is empty.

Moveq instructions:

If self is empty, the selector is also set to null.

Bx instructions:

In arm, bx lr is used to return to the place where the subroutine is called (that is, return to the caller). If self is empty, it is returned to the place where objc_msgSend is called for further execution.

In short:

If the self parameter passed to objc_msgSend is nil, this function will not perform meaningful operations and will return directly.

Related Article

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.