-3
long cread(long *xp) {
  return (xp? *xp : 0);
}

It is invalid since it could attempt to read from a null address

So the solution suggested this code

long cread_alt(long *xp){
  long tem = 0;
  if(*xp > 0){
   tem = *xp;
  }
  return tem;

But I think it is also not valid since if(*xp > 0) is still defective when the xp is pointing a null address.

So I thought this code

 long cread_alt2(long *xp){
     long tem = 0;
     if(xp != NULL){
        tem = *xp;
     }
     return tem;
 }

Do I have this correct?

3 Answers3

6
long cread(long *xp) {
  return (xp? *xp : 0);
}

is valid and this is a very common technique. The expression pointer_name can be converted to a bool and will be false if pointer_name == nullptr and true if pointer_name != nullptr. That means for the above code that *xp only occurs when you do not have a null pointer.

int cread_alt2(long *xp){
    long tem = 0;
    if(xp != NULL){
        tem = *xp;
    }
    return tem;
}

Does the same thing, it is just much more verbose about it. So, the only code that is actually invalid is cread_alt, which does dereference xp without first checking if it is null or not.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • `cread_alt2()` also converts a `long` to an `int` on `return`. It only does the same thing as `cread()` if `int` supports at least the range of values that `long` does, which is not required by the standard. – Peter Oct 12 '18 at 21:31
  • @Peter It was probably a typo from the OP. I'll ask and if it is I'll update the code. – NathanOliver Oct 12 '18 at 21:32
2

Use of

if(xp != NULL){
  tem = *xp;
}

is valid. However, in your second snippet, you have

if(*xp > 0){
  tem = *xp;
}

Perhaps you want to use both.

if ( xp != NULL && *xp > 0 )
{
   tem = *xp;
}

If you are able to use C++11 or later, it is better coding practice to use nullptr instead of NULL.

if ( xp != nullptr && *xp > 0 )
{
   tem = *xp;
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

The original function is 100% valid code and it never dereferences the NULL pointer.

I think you should read the chapter about the ternary operators from your favourite C book

0___________
  • 60,014
  • 4
  • 34
  • 74