在此函数中有缺陷,因为取消引用null无效,所以我想更改代码

KFC*_*KFC -3 c++ pointers null-pointer dereference

long cread(long *xp) {
  return (xp? *xp : 0);
}
Run Code Online (Sandbox Code Playgroud)

它无效,因为它可能尝试从空地址读取

所以解决方案建议使用此代码

long cread_alt(long *xp){
  long tem = 0;
  if(*xp > 0){
   tem = *xp;
  }
  return tem;
Run Code Online (Sandbox Code Playgroud)

但我认为它也无效,因为if(*xp > 0)xp指向空地址时仍然有缺陷.

所以我想到了这段代码

 long cread_alt2(long *xp){
     long tem = 0;
     if(xp != NULL){
        tem = *xp;
     }
     return tem;
 }
Run Code Online (Sandbox Code Playgroud)

我有这个吗?

Nat*_*ica 6

long cread(long *xp) {
  return (xp? *xp : 0);
}
Run Code Online (Sandbox Code Playgroud)

有效的,这是一种非常常见的技术.表达式pointer_name可以转换为a bool,falseif if pointer_name == nullptrtrueif pointer_name != nullptr.这意味着*xp只有在没有空指针时才会出现上述代码.

int cread_alt2(long *xp){
    long tem = 0;
    if(xp != NULL){
        tem = *xp;
    }
    return tem;
}
Run Code Online (Sandbox Code Playgroud)

同样的事情,它只是更加冗长.因此,唯一实际上无效的代码是cread_alt,在xp没有首先检查它是否为空的情况下进行解除引用.