开发者

Dereference of null pointer, but I am not using pointers

I did the "Build and analyze" in xCode and get "Dereference of null pointer" when setting a normal int to 0 in my init-method. I noted in my code below for which row I get the message. I'm developing for 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's 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:(NS开发者_运维技巧String *)clr;

@end

It's not the complete code, pasted what I think is useful.

Since I am not using a pointer I find this quite strange. How come I get this message?

Thanks and Regards, Niklas


The first if statement in your init method is checking whether or not [super init] returns nil. (Technically it should be written if ((self = [super init])), which the new LLVM compiler will warn you about).

The static analyser is checking ALL possible code paths, even the case where [super init] returns nil. In this case, your if statement fails and self is nil. If self is nil then its instance variables aren't accessible.

To fix this, you need to place your initialisations inside the if statement with the image initialisation and then return self outside the if statement.


Have you declared it as a property? I'm not sure if it's necessary in this case but you haven't made accessor methods (although I think you are still setting the instance variable directly...)

i.e., 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 doesn't deal with while loops very effectively. Anyway, see what happens if you add those lines of code and get back to me.


Your init method is wrong.

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's for this line I get the message
        stepY = 0;
        oldX = 0;
        color = [[NSString alloc]initWithString:clr];
        visible = YES;
        copied = NO;
    }   
    return self;
}

I assume the message you are getting is from the static analyser. As stepX is an instance variable, the line

stepX = 0;

is really shorthand for

self->stepX = 0;

where -> has its normal C meaning. As that line is outside the test that self is non nil in your code, the static analyser is flagging an issue.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜