Check null pointer

I am building an iphone application and using C ++, and I am having trouble checking if the 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 installed or not installed, it still goes into every statement and gives me

Software received signal: "EXC_BAD_ACCESS".

How can I check if myInterface is null

+4
source share
3 answers

Your main problem is that you did not initialize myInterface .

Assuming myInterfacee is just a typo, everything will be fine, and none of them will 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 do not like the fourth, but this is a matter of style, not correctness.

If myInterface is installed or not installed is still included in each statement

I kind of don't believe it, but if it really is (you initialize myInterface and you still see that both the if (!myInterface) and if (myInterface != 0) ), that is, something very wrong in elsewhere in your program. Those tests have opposite meanings, so the only way they will both look is when something undefined happens.

+17
source

You do not initialize myInterface , so its value is undefined. You must initialize it to zero:

 IMyInterface* myInterface = 0; 

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

 IMyInterface* myInterface = new TypeImplementingInterface(); 

You should also consider using smart pointers, such as shared_ptr ; smart pointers simplify memory management in C ++.

+6
source

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

+4
source

All Articles