user346443
user346443

Reputation: 4862

Check for null pointer

I'm building a iphone app and using c++ and am having trouble checking if a pointer is null.

IMyInterface* myInterface;

if ( !myInterface ){                         //doesn't work
     myInterfacee->doSometing(); 
}

if ( myInterface != 0 ) {                    //doesn't work 
     myInterfacee->doSometing(); 
}

if ( myInterface != NULL ){                  //doesn't work
     myInterfacee->doSometing(); 
}

if ( myInterface != ( myInterface* )0 ) {    //doesn't work 
     myInterfacee->doSometing(); 
}

If myInterface is or isn't set it still enters each statement and gives me

Program received signal: “EXC_BAD_ACCESS”.

How do i go about checking if myInterface is null

Upvotes: 4

Views: 3336

Answers (3)

Steve Jessop
Steve Jessop

Reputation: 279435

Your basic problem here is that you haven't initialized myInterface.

Assuming myInterfacee is just a typo, the following would all be fine, and none of them would call doSometing:

IMyInterface* myInterface = 0;

if ( myInterface ){                // ! removed
     myInterface->doSometing(); 
}

if ( myInterface != 0 ) {          // as before
     myInterface->doSometing(); 
}

if ( myInterface != NULL ){        // as before
    myInterface->doSometing(); 
}

if ( myInterface != ( IMyInterface* )0 ) { // IMyInterface, not myInterface
     myInterface->doSometing(); 
}

Personally, I prefer the first two over the third, and don't like the fourth at all, but that's a question of style rather than correctness.

If myInterface is or isn't set it still enters each statement

I sort of disbelieve this, but if that's really the case (you're initializing myInterface, and still seeing that both the if (!myInterface) and the if (myInterface != 0) clauses are executed), then there is something very wrong elsewhere in your program. Those tests have opposite meanings, so the only way they're both going to appear true is when something undefined is going on.

Upvotes: 17

James McNellis
James McNellis

Reputation: 355357

You do not initialize myInterface, so its value is indeterminate. You need to initialize it to null:

IMyInterface* myInterface = 0;

Or, if you can, it is usually preferable to initialize the variable to a valid state when you declare it:

IMyInterface* myInterface = new TypeImplementingInterface();

You should also consider using smart pointers of some kind, like shared_ptr; smart pointers make memory management in C++ far simpler.

Upvotes: 6

nonVirtualThunk
nonVirtualThunk

Reputation: 2852

Your problem is that pointers are not automatically initialized to NULL by default. All of the methods you have there should work, but you'll need to initialize your variable to be NULL when you define it.

Upvotes: 4

Related Questions