Reputation: 1
I want to know necessity of null check.
Sample code is following
#include <iostream>
bool twice( int* a )
{
if( a == nullptr )
{
std::cout << "null" << std::endl;
return true;
}
std::cout << *a << std::endl;
*a *= 2;
std::cout << *a << std::endl;
return false;
}
int main()
{
twice( nullptr );
int v = 16;
std::cout << v << std::endl;
twice( &v );
std::cout << v << std::endl;
}
This is output
null
16
16
32
32
I recognize that 'nullptr' is "the pointer that point out address zero of memory" or "Flag when reference of pointer variable is invalid".
Q1. address zero of memory is only one per real memory?
Q2. Can you reproduce "reference of pointer variable is invalid" on this code?
Q3. What kind of function does the pointer variable reference become invalid?
Sorry, my poor English.
Upvotes: 0
Views: 157
Reputation: 21
Pointer is just the unsigned integer that points to memory address. ln some system having virtual memory, the first page of the memory will not be mapped to physical memory.so, when we are trying to read/write at null pointer address it causes segmentation fault/ page fault. However in some embedded devices we will not observe the segmentation fault issue as we could access the zero memory space
Irrespective of the os,To avoid application crash, adding null pointer check is good practice
Upvotes: 0
Reputation: 373462
I would recommend thinking about this in a different way. Rather thinking of a null pointer as "memory address zero," think of it as "this pointer does not actually point at anything."
With that mental model, there's a clearer reason why you need the null check. If you have a pointer that doesn't actually point at anything, then writing
*a *= 2;
is a meaningless operation - there is no thing being pointed at by a
, so dereferencing a
to get an integer and then doubling that integer isn't a well-defined operation.
Internally, on most systems, yes nullptr
is implemented as "a pointer to memory address zero, which is considered invalid on most operating systems," but I don't think that sheds much light on why this code needs the null check.
Upvotes: 2