简体   繁体   English

Objective-C未分配的指针

[英]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. 我对Objective-C中的nil感到困惑,因为apple表示可以将消息发送到nil对象。

so suppose this code : 所以假设这段代码:

Foo * myFoo;
[myFoo doSomeStuff];

in Xcode this doesn't crash so why? 在Xcode中不会崩溃,为什么呢? does unallocated pointer in objective-C is the same as nil. 在objective-C中未分配的指针与nil相同。

Thanks. 谢谢。

Because there's a difference between nil and random garbage . 因为nilrandom garbage之间是有区别的。 You see, this line: 您会看到这一行:

Foo * myFoo;

does not make any guarantee for the value of myFoo if you don't explicitly set one. 如果您未明确设置myFoo的值,则不做任何保证。 Try for yourself: 自己尝试:

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

It is likely that it won't print 0 ; 它可能不会打印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). Objective-C运行时将允许对nil调用工作,但nil严格定义为零:因此,您必须将变量初始化为nil才能使用此功能(否则,您可能会遇到分段错误,因为消息传递随机地址不利于您的程序)。

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. 实例变量,全局变量或静态变量将初始化为nil,除非您将其初始化为其他变量。 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. 请注意, 通常这并非总是如此 -当您谈论未定义的行为时,几乎所有可能的事情都可能发生,包括崩溃,发往错误对象的消息,或在大多数情况下似乎正确且随机失败的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM