开发者

Pointer vs nil initialized pointer

just trying to understand ObjectiveC a bit better.

Shouldn't this two expressions be the same?

NSString *str;开发者_运维知识库 //address of str is 0x438a5625
NSString *str=nil; //address of str is 0x0

What is the reason for this behavior?


In C, and hence Objective C, variables are not automatically initialized; but rather, you are just assigned the memory, and clearing it (if necessary) becomes your responsibility.

Sometimes, this memory is already clear, but most of the time, it's filled with garbage, freed memory from other processes, or elephants dancing the can-can; the contents of uninitialized automatic memory (such as what you are having here) is undefined.

Never assume that uninitialized memory is in fact usable for anything other than assigning a value to!

As a point of order, in both cases you are saying "address" when you really mean "value".


The result for the second expression is clear nil == 0x0 thus the value of str is 0x0. The first expression has, in general, an undefined value (meaning could have any value). It depends on the compiler what value an uninitialized variable has. Some compilers will set uninitialized variables to 0 (0x0), but it is not always the case. In general, compilers will not set the value to anything and the variable will contain any value the chunk of memory you got had.

The specifics of the Objective-C compiler in the iOS SDK are not really relevant. The best practice is not to assume variables get a default initial value. Therefore, the second line is a much better way to initialize a variable you don't plan to use right away. Otherwise you may bump into unexpected behaviors along the road when you change compiler, when the compiler changes, or when your variable gets initialized to a different value.


In C, stack allocated variables are not initialized to zero bytes by default, whereas globals and Objective C objects (allocated with alloc) are.

I guess it's a performance concern, and it's warned against in just about every textbook on C and derived languages. The compiler should warn you as well, if you refer to the local variable without assigning a value to it first.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜