A point that most of the answers here are not addressing, at least not explicitly, is that a null pointer is a value that exists during execution, and a null pointer constant is a syntactic construct that exists in C source code.
A null pointer constant, as Karlson's answer correctly states, is either an integer constant expression with the value 0 (a simple 0
is the most common example), or such an expression cast to void*
(such as (void*)0
).
NULL
is a macro, defined in <stddef.h>
and several other standard headers, that expands to an implementation-defined null pointer constant. The expansion is typically either 0
or ((void*)0)
(the outer parentheses are needed to satisfy other language rules).
So a literal 0
, when used in a context that requires an expression of pointer type, always evaluates to a null pointer, i.e., a unique pointer value that points to no object. That does not imply anything about the representation of a null pointer. Null pointers are very commonly represented as all-bits-zero, but they can be represented as anything. But even if a null pointer is represented as 0xDEADBEEF
, 0
or (void*)0
is still a null pointer constant.
This answer to the question on stackoverflow covers this well.
This implies, among other things, that memset()
or calloc()
, which can set a region of memory to all-bits-zero, will not necessarily set any pointers in that region to null pointers. They're likely to do so on most implementations, perhaps even all existing ones, but the language doesn't guarantee it.
This question is really a duplicate of this one, but Stack Exchange doesn't allow marking duplicates across sites.
It depends on the 'contract':
If PowerManager
MUST have a valid IMsgSender
, never check for null, let it die sooner.
If on the other hand, it MAY have a IMsgSender
, then you need to check every time you use, as simple as that.
Final comment about the story of the junior programmer, the problem is actually the lack of testing procedures.
Best Answer
The value of the assertion is:
GetMeAPikachu
returns non-null. This is especially valuable if the function at some point in history changed behavior, or if there are specific circumstances in which the function can return null, but the programmer is asserting that these circumstances don't apply here.ThunderBolt
. If that function isn't virtual and doesn't access member variables itself, the crash could simply not happen at all, or be deep within the call tree, and it might be not an access violation, but possibly an illegal instruction because you eventually managed to jump through an invalid function pointer/vtable.