is this line correct runtime?
At every point in the program where you are dereferencing a pointer, you
*must know* that the pointer is not null. How you come by that knowledge
is varied. You don't need to check every time with an 'if' statement
unless you cannot know any other way. One option would be to simply look
at the code and make sure that there is no way that the pointer could be
bad, for example:
void fn() {
char* c = new char[20];
*c = 'a'; // I just know that 'c' isn't null, I don't have to check
}
void fn( char* c ) {
if ( c )
*c = 'a'; // I know that 'c' isn't null here because
// I have an 'if' statement that ensures it
}
Of course this requires that you are able to look at *all* the relevant
code, but what if you can't? Then you can make it a design rule that
others must ensure the pointer isn't null, for example:
void fn( char* c ) {
// 'c' must not be null when calling this function
assert( c );
*c = 'a';
}
I would never do something like this:
int fn( char* c ) {
if ( !c ) return 0; // fail
*c = 'a';
return 1; // succeed
}
or any exception throwing counterpart. Instead I would use the design
rule method above. The reason is because the code calling 'fn' can
easily check to see if 'c' is null before passing it in if it doesn't
know, and it also must decide what to do in the case where 'c' is null.
Putting in the if check here simply adds useless redundancy.
first run a class member (maybe unallocated)
and then check if class memory allocated (if not crashes)
Don't ever dereference a pointer unless you know that it will be valid.