问题
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