检查 char* 是否为 null 或为空时取消引用 NULL 指针警告

ivi*_*jcb 1 c++ pointers dereference

简单地说,我正在通过if语句检查两个 char* 是否为 nullptr 或为空,但我收到一条警告,说我正在取消引用一个空指针。

// mplate is a reference to a class
if ((mplate.m_plate != nullptr || mplate.m_plate[0] != '\0') || (plate != nullptr || plate[0] != '\0')) {
// Do something
}
else {
// do something else
}
Run Code Online (Sandbox Code Playgroud)

所以基本上我想在if声明中说的是,如果要么mplate.mplateplate为空,要么nullptr这样做,否则做其他事情。

Severity    Code    Description Project File    Line    Suppression State
Warning C6011   Dereferencing NULL pointer 'make'.
Warning C6011   Dereferencing NULL pointer 'model'.
Warning C6011   Dereferencing NULL pointer 'mplate.m_plate'.
Warning C6011   Dereferencing NULL pointer 'plate'.
Warning C6011   Dereferencing NULL pointer 'plate'.
Run Code Online (Sandbox Code Playgroud)

cig*_*ien 8

你正在做类似的事情

if (p != nullptr || *p)
Run Code Online (Sandbox Code Playgroud)

只有当指针是nullptr. 这意味着如果指针有效,您什么都不做,或者如果指针无效(即 UB),则取消引用。

你需要做一个合乎逻辑的事情and,就像这样

if (p != nullptr && *p)
Run Code Online (Sandbox Code Playgroud)

即只有在指针不是 时才取消引用nullptr