Is null pointer dereference undefined behavior in Objective-C?

安稳与你 提交于 2020-01-05 07:27:21

问题


In C and C++, null pointer dereference is undefined behavior. What about Objective-C?

In other words, what is this code guaranteed to do?

*(long*)0 = 0;

Background: I wonder if this answer might trigger undefined behavior potentially causing random things like the statement being optimized out or even weirder things.

Of course, I do not endorse doing this. Still, it is important to know the rules of the language.


回答1:


Since Objective-C is nothing more than an object-oriented layer on top of C, pure C statements don't have special additional meanings. According to this, in this case, *(long*)0 = 0; is evaluated and interpreted just like in C (since it is C) and thus it invokes undefined behavior. As such, it is not guaranteed to do anything.




回答2:


Dereferencing a null pointer remains undefined in Objective-C.

The only caveat is that messaging doesn't require a dereference. Messaging to a null pointer (or nil in Objective-C terms) is always explicitly safe and defined to return a further null pointer.

Hence compound messaging, like [[class alloc] init], is always explicitly safe.




回答3:


The only thing that statement is guaranteed to do is invoke undefined behavior.

It may be guaranteed to do something specific on a specific platform with a specific compiler.




回答4:


a strcpy(0, "bla") as seen in that answer has crashed always and I dont see how that can not work - or be optimized away by the compiler.



来源:https://stackoverflow.com/questions/13651642/is-null-pointer-dereference-undefined-behavior-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!