what is a null pointer in c - Stack Overflow
Why do we use Null pointers?
C and null pointers
C compilers don't do this analysis built-in because
-
they don't need to; the C spec doesn't expect compilers to catch U.B. at compile time
-
beyond trivial examples like this, it's hard to be completely certain that it actually 100% will be undefined behavior -- for example, this code is perfectly valid as long as it is never reached (the branch that contains it never runs, or the function that contains it isn't called)
-
lots of programs generate C code as output, and they might contain "bad" code like this but be fine because the generation ensures it's never actually reached
-
there's also the small possibility that for the particular system you're targeting, this has defined behavior (such as invoking some particular hardware trap); so it can't always be a compile error
-
-
it's hard to make it work beyond trivial examples like this
-
and as a result would almost never flag anything in real code written by experience C programmers
Experienced C programmers do make mistakes with undefined behavior, but usually not in such an obviously and automatically recognizable case as this. There certainly is a lot of research into detecting potential bugs in C code at compile time, but it's generally too slow to run as a part of normal compilation.
More on reddit.comDifference between NUL(for string) vs NULL(for pointer) in c++
Any pointer type with the value 0 is called a null pointer. Here is the explanation from the C standard ยง6.3.2.3:
- An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function
Null pointer is a pointer that points to memory address 0. Most system reserve this address so that no object will ever reside in there. This reservation allows to use it as blank address.
If you try to read or write from null pointer you will get runtime error which is sometimes called segmentation fault, or null pointer exception.
In your example the null pointer is used to indicate end of the list. So this condition (struct entry *) 0, checks if you have reached end of the list and iteration should stop
Usually it considered better form to use constant NULL instead of literal value 0. This makes code more readable, and also covers very rare case when NULL pointer is not a 0
The cast (struct entry *) is just to avoid compiler warning, because literal 0 is of type integer not a pointer. That's another reason to use constant NULL, because it is usually defined as (void*) 0 which compares nicely to any pointer value without a warning from compiler
If we want to "Nullify" something why dont we create a pointer in a controlled way that points to value 0?