开发者

Objective-C unallocated pointer

i'm confusing about nil in objective-C, cause apple said that it's ok to send a message to a nil object.

so suppose this code :

Foo * myFoo;
[myFoo doSomeStuff];

in Xcode this doesn't crash so why? does unallocated pointer in obje开发者_运维技巧ctive-C is the same as nil.

Thanks.


Because there's a difference between nil and random garbage. You see, this line:

Foo * myFoo;

does not make any guarantee for the value of myFoo if you don't explicitly set one. Try for yourself:

Foo* myFoo;
printf("%x\n", myFoo);

It is likely that it won't print 0; instead, it will print the last thing that happened to be at that memory location. (It might be zero. But it very well may not be.)

Local variables have an undefined value before you assign them one by yourself. The Objective-C runtime will let calls to nil work, but nil is strictly defined to be zero: therefore, you have to initialize your variables to nil to use this feature (otherwise, you're likely to get a segmentation fault, because messaging a random address isn't good for your program).

This will always "work" (by "work" I mean not crash):

Foo* myFoo = nil;
[myFoo whatever];

Here is an example program that, with my machine, consistently doesn't have zeroed pointers:

#include <stdio.h>
#include <string.h>

struct random_stuff
{
    int stuff[60];
};

struct random_stuff scramble()
{
    int filler = 0xdeadbeef;
    struct random_stuff foo;

    memset_pattern4(&foo.stuff, &filler, sizeof foo);
    return foo;
}

void print()
{
    void* pointer[30];
    for (int i = 0; i < 30; i++)
        printf("%p\n", pointer[i]);
}

int main()
{
    scramble();
    print();
}


It depends on the variable. An instance variable, global variable or static variable will be initialized to nil unless you initialize it to something else. An ordinary local variable is not initialized to any defined value, and messaging a variable like that will usually crash. Note that that's usually, not always — when you're talking about undefined behavior, just about anything is possible, including crashes, messages going to the wrong objects, or behavior that seems correct most of the time and fails at random.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜