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

标签 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
}

所以基本上我想在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'.

最佳答案

你正在做类似的事情

if (p != nullptr || *p)

也就是说,仅当指针为nullptr时,您才取消引用。这意味着如果指针有效,则不执行任何操作;如果指针无效(即UB),则取消引用。

您需要像这样执行逻辑and
if (p != nullptr && *p)

即仅在指针不是nullptr时才取消引用。

关于c++ - 检查char *是否为null或为空时取消引用NULL指针警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61189312/

相关文章:

c - 多叉树的结构 - C

c++ - 将代码声明转化为文字(引用运算符和取消引用运算符混淆)

c - 我应该如何在心理上解析这个陈述?

c++ - 我怎样才能找出这个 ffmpeg 错误代码的含义?

c++ - Visual Studio C++ 2k15 - 指针地址出错

c - 返回主函数指针时数据被重置 c/linux

c - 如何将 argv[k] 变成另一个字符串?

不能取消引用变量所以函数满足

c++ - 我怎样才能创建 vector 的直方图<vector<long>>

c++ - 无法理解为什么 for-loop 运行 5 次而不是 4 次