Parsing a null pointer, but I don't use pointers

I did "Build and analysis" in xCode and got a "Dereference of null pointer" when setting the normal int to 0 in my init method. I noticed in my code below for which line I am receiving the message. I am developing for the iPhone.

Bric.m

#import "Bric.h" @implementation Bric - (id)initWithImage:(UIImage *)img:(NSString*)clr{ if (self = [super init]) { image = [[UIImageView alloc] initWithImage:img]; } stepX = 0; //It for this line I get the message stepY = 0; oldX = 0; color = [[NSString alloc]initWithString:clr]; visible = YES; copied = NO; return self; } @end 

Bric.h

 #import <Foundation/Foundation.h> @interface Bric : NSObject { int stepX; int stepY; } -(id)initWithImage:(UIImage *)img:(NSString *)clr; @end 

This is not the complete code inserted, in my opinion, useful.

Since I do not use a pointer, I find it rather strange. Why did I receive this message?

Thanks and Regards, Niklas

+7
debugging objective-c iphone xcode code-analysis
source share
3 answers

The first if in the init method checks to see if [super init] nil . (Technically, this should be written if ((self = [super init])) , which the new LLVM compiler warns you about.)

The static analyzer checks ALL possible code paths, even when [super init] returns nil. In this case, your if fails, and self is nil . If self is nil , then its instance variables are not available.

To fix this, you need to put your initializations inside the if with the image initialization, and then return self outside the if statement.

+20
source share

Did you declare it as property? I am not sure if this is necessary in this case, but you did not make access methods (although I think that you are still setting the instance variable directly)

ie, in your header file,

 @property int stepX; 

and in your .m file,

 @synthesize stepX; 

This will allow you to access the variable as self.stepX and self.stepY. Sometimes the analyzer makes mistakes, though ... I noticed that it does not deal with while loops very efficiently. In any case, see what happens if you add these lines of code and come back to me.

0
source share

Your init method is invalid.

It should look like this:

 - (id)initWithImage:(UIImage *)img:(NSString*)clr { if (self = [super init]) // NB, this line should give you a waring { image = [[UIImageView alloc] initWithImage:img]; stepX = 0; //It for this line I get the message stepY = 0; oldX = 0; color = [[NSString alloc]initWithString:clr]; visible = YES; copied = NO; } return self; } 

I assume that the message you receive is related to a static analyzer. Since stepX is an instance variable, the line

 stepX = 0; 

really shrinking for

 self->stepX = 0; 

where -> has its normal meaning C. Since this line goes beyond the test, which itself is not zero in your code, the static analyzer poses a problem.

0
source share

All Articles