1

Possible Duplicate:
Declared but unset variable evaluates as true?

Why does this code work on Mac OS

int main (int argc, const char * argv[]) 
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    NSString *str;
    NSLog(@"%@", [str length]);

    NSLog(@"Hello, World!");
    [pool drain];
    return 0;
}

and console output is

2011-09-23 15:37:17.481 Untitled1[80021:903] (null) 
2011-09-23 15:37:17.495 Untitled1[80021:903] Hello, World!

but crashes on iPhone ?

Community
  • 1
  • 1
orsi
  • 159
  • 10

5 Answers5

3

Two mistakes.
First, you declare pointer str, don't set it's value and use it in NSLog.
Second, you use formatting %@, but supply integer value ([str length]), result is undefined. That's why on simulator it prints null, but crashes on device.

Valeriy Van
  • 1,851
  • 16
  • 19
3

You were just lucky. Local variables are uninitialised and could contain anything. It's likely that on OS X, str contains 0 (aka nil), sending -length to nil returns 0. Then you are treating the length (which is an NSInteger) as a pointer for the NSLog.

If the length is 0, the NSLog will treat it as a nil pointer if the format specifier is %@ and will print (null).

If str has a random non zero value, either your program will crash when you send length or if it miraculously works and returns a non zero length, it'll probably crash trying to treat it as an object pointer in NSLog

JeremyP
  • 84,577
  • 15
  • 123
  • 161
1

the value is never initialized (or set). it could be any random value. in debug, it may be zero-iniitalized.

a crash (or some UB) is what you should expect in this case. so... turn up your compiler and static analyzer warnings, fix the issues, and always initialize your values.

justin
  • 104,054
  • 14
  • 179
  • 226
0

try this.

     NSString *str=@"";

NSLog(@"%d", [str length]);
Arun
  • 2,271
  • 1
  • 14
  • 18
-2

See , You can call only release method over a nil object. other than release method we cannot call any method over a nil.

Here you are calling a method ( length )over an object which is pointing to nil , in this case it should point to nsstring object in general before sending length message .

Ramesh India
  • 107
  • 2
  • 13