Reputation: 307
I want to evaluate a pointer is null or not by an if condition like below :
Model * model;
if(model == nullptr){
//do something...
}
But this does not work, Strangly the model pointer instead of pointing to 0x0
location it points to 0xcdcdcdcdcdcdcdcd memory location then model==nullptr
doesn't work for that , i also did if(model)
, if(model== NULL)
these are also not working!
any idea about this problem ?
Upvotes: 1
Views: 748
Reputation: 1665
The pointer Model * model;
will take any random garbage value depending on the memory location at which the pointer gets allocated. C/C++ standards do not mandate that declared but uninitialized pointers be automatically initialized to NULL (or any default value).
Now, I'm not really clear why the pointer is compared to NULL immediately after declaration, but that comparison makes sense after the pointer is assigned a value returned by a function or some expression:
Model * model = some_func(/* .. */); // This would be
if (model == NULL) { // a valid usage
}
Upvotes: 0
Reputation: 106012
An uninitialized pointer need not point to NULL
. It can point anywhere.
Upvotes: 7
Reputation: 73366
This code invokes Undefined Behavior, since your pointer is uninitialized!
You need to initialize your pointer to nullptr
, and then check for it, otherwise, its value is garbage (it can be anything).
PS: Null pointers must compare equal to the expression 0x0
.
Upvotes: 1
Reputation: 195
which IDE you are using if you are using Visual Studio it use NULL like this
but here is the solution
Model * model=NULL;
if(model == NULL){
//do something...
}
Upvotes: -3