Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for null pointer

Tags:

c++

null

pointers

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

like image 659
user346443 Avatar asked Nov 28 '22 18:11

user346443


1 Answers

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.

like image 107
Steve Jessop Avatar answered Dec 05 '22 11:12

Steve Jessop