1

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 ?

1
  • 2
    Please stop spamming irrelevant tags. There is no nullptr in c. Commented Sep 26, 2017 at 6:04

4 Answers 4

7

An uninitialized pointer need not point to NULL. It can point anywhere.

Sign up to request clarification or add additional context in comments.

1 Comment

@M.M That is true, but for that you need to set the pointer to nullptr at some point. Until then it is uninitialized, and its contents are determined by the implementation
1

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.

Comments

0

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
}

Comments

-3

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...
}

2 Comments

Despite being quite slow to support latest C++ standard revisions properly, nullptr is supported in MSVC for quite some time. Ever since they started supporting C++11.
it is not the IDE but the compiler that does support C++11 or not

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.