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)
我有这个吗?
long cread(long *xp) {
return (xp? *xp : 0);
}
Run Code Online (Sandbox Code Playgroud)
是有效的,这是一种非常常见的技术.表达式pointer_name可以转换为a bool,falseif if pointer_name == nullptr和trueif 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没有首先检查它是否为空的情况下进行解除引用.