Checking for NULL pointer in C/C++
In my experience, tests of the form if (ptr)
or if (!ptr)
are preferred. They do not depend on the definition of the symbol NULL
. They do not expose the opportunity for the accidental assignment. And they are clear and succinct.
Edit: As SoapBox points out in a comment, they are compatible with C++ classes such as auto_ptr
that are objects that act as pointers and which provide a conversion to bool
to enable exactly this idiom. For these objects, an explicit comparison to NULL
would have to invoke a conversion to pointer which may have other semantic side effects or be more expensive than the simple existence check that the bool
conversion implies.
I have a preference for code that says what it means without unneeded text. if (ptr != NULL)
has the same meaning as if (ptr)
but at the cost of redundant specificity. The next logical thing is to write if ((ptr != NULL) == TRUE)
and that way lies madness. The C language is clear that a boolean tested by if
, while
or the like has a specific meaning of non-zero value is true and zero is false. Redundancy does not make it clearer.
How to check for NULL pointer in C?
According to De_Morgan's_laws
(not (A and B) = not A or not B)
Your condition
if (!(s1 && s2))
is the same as
if (!s1 || !s2)) //same as if (s1 == NULL || s2 == NULL)
Here you are checking if any of s1
or s2
is NULL
and if so you exit.
But in second one
if (s1 == NULL && s2 == NULL)
return EXIT_FAILURE;
if both s1
and s2
are NULL
then you are exiting.
If any of s1
or s2
are not NULL
you will proceed further and will try to access them, thus invoking undefined behavior.
Null pointer check via myPtr 0
Ordered comparison between a pointer and an integer is ill-formed in C++ (even when the integer is a null pointer constant such as it is in this case). The risk is that compilers are allowed to, and do, refuse to compile such code.
You can rewrite it as either of these:
if(myPtr != nullptr)
if(myPtr)
What is the best practice to check if an object is null in C++
I want to check if the object is null.
Congratulations, your Object object
is not null. null is not a possible value for object
to be.
A close analog might be to test that it is different to a default-constructed Object
, if Object
is default-constructable.
EXPECT_TRUE(my_object != Object{})
Checking null pointer && pointer- member value in the same if statement
...is it allowed to check that a pointer is not null and (&&) to also check one of its members value in the same if statement?
It's perfectly valid, it is not UB, the expression is evaluated from left to right, if the left part of the expression evaluates to false
the right part is not evaluated. This is usually called operator short circuit.
The rationale is that if the first part is false
, there is no possibilty of the whole expression being true
, false && false
is false
, false && true
is also false
.
...if I write it as 2 separate if to make it more readable, can I expect the compiler to optimize it into a single if?
In light of the above answer, you wouldn't need two if
s, I would argue that it will not make your code more readable, I prefer the way you have it right know, in any case this is only my opinion. About the compiler, I wouldn't think that there will be much difference either way, as sampled in this live demo.
In either C or C++, should I check pointer parameters against NULL/nullptr?
While in general I don't see the value in detecting NULL (why NULL and not some other invalid address?) for a public API I'd probably still do it simply because many C and C++ programmers expect such behavior.
Check for NULL pointer doesn't work for char pointer
You declared an array of pointers with static storage duration.
static char *sys_efile[FILE_PATH_SIZE];
So all elements of the array are implicitly initialized as null-pointers. But the array itself can not be implicitly converted to a null pointer because it occupies memory. So this statement
if (sys_efile == NULL)
will always evaluate to false.
Either actually instead of the array of pointers you want to declare a character array like
static char sys_efile[FILE_PATH_SIZE]; // 100
and then you may write for example
// issue_main.c
#include "issue.h"
if ( *sys_efile == '\0' )
return -EFAULT;
file = filp_open( sys_efile, O_RDWR, 0);
Or if you are going to use an array of pointers then the if statement should look like
static char *sys_efile[FILE_PATH_SIZE]; // 100
// issue_main.c
#include "issue.h"
if ( *sys_efile == NULL)
return -EFAULT;
file = filp_open(*sys_efile, O_RDWR, 0);
How to check if void pointer points to NULL?
I'd simply write if (!ptr)
.
NULL
is basically just 0
and !0
is true.
Dereferencing NULL pointer warning when checking if char* is null or empty
You are doing something like
if (p != nullptr || *p)
i.e. you are dereferencing only if the pointer is nullptr
. This means you do nothing if the pointer is valid, or you dereference if it's invalid (which is UB).
You need to do a logical and
instead, like this
if (p != nullptr && *p)
i.e. only dereference if the pointer is not nullptr
.
Related Topics
How to Catch the Null Pointer Exception
Undefined Symbols "Vtable for ..." and "Typeinfo For..."
Colorizing Text in the Console with C++
Qt: Resizing a Qlabel Containing a Qpixmap While Keeping Its Aspect Ratio
Invalid Conversion from 'Void*' to 'Char*' When Using Malloc
Returning a Pointer of a Local Variable C++
What Does the "Lock" Instruction Mean in X86 Assembly
How to Evaluate Mathematical Expressions in C++
C++: Can a MACro Expand "Abc" into 'A', 'B', 'C'
Iterating Over a Struct in C++
Is Right Shift Undefined Behavior If the Count Is Larger Than the Width of the Type
Drawing Sphere in Opengl Without Using Glusphere()
When Is It Best to Use the Stack Instead of the Heap and Vice Versa
Why Does Auto X{3} Deduce an Initializer_List
Is Auto as a Parameter in a Regular Function a Gcc 4.9 Extension