c - 允许在信任边界进行冗余空指针检查

标签 c clang static-analysis

我最近在查看一些代码,其中 clang 由于 -Wtautological-pointer-compare 而生成警告。

代码可以简化为:

void foo(const char*s) __attribute__((nonnull)) {
   if (s) { /* Test added just in case*/
      if (s[0]=='a') s[0]='b'; /* Dummy code using the pointer */
   }
}

显然,如果我们信任这些属性,那么 s 就不能为 null,并且警告是多余的。然而,对我来说,似乎最好处理函数中的空指针(因为我们不能相信调用代码是用这些警告编译的,或者人们阅读警告)——同时仍然检测代码中的其他空指针问题。

因此禁用此警告(对整个函数使用 pragma)似乎不是最佳选择。

在带有 SAL 的 Visual Studio 中,您似乎可以使用 _In_ _Pre_defensive_ 来处理 这个案例。

In that case, _In_ _Pre_defensive_ is preferred at a trust boundary to indicate that although a caller will get an error if it attempts to pass NULL, the function body will be analyzed as if the parameter might be NULL, and any attempts to de-reference the pointer without first checking it for NULL will be flagged.

用 clang 可以做类似的事情吗?

最佳答案

请注意,这个问题比只看到不需要的警告更糟糕。由于该函数具有该属性,编译器将删除 if,就好像您这样写:

if (true)

因为您 promise 指针不会为NULL。所以你的空检查没有效果。见:

https://godbolt.org/z/l8w4x1

int func(void* ptr) __attribute__((nonnull))
{
    if (ptr)
        return 1;
    return 0;
}

无条件返回1:

mov eax, 1
ret

所以你应该认真对待这个警告。

除了使用 -fno-delete-null-pointer-checks 进行编译以防止空指针检查被优化和 -Wno 之外,我不知道有任何解决方法-tautological-pointer-compare 使警告静音。显然,您不想在全局范围内使用这些标志。因此,您应该将具有此属性的函数合并到它们自己的源文件中,并且仅在编译该文件时使用这些标志。

关于c - 允许在信任边界进行冗余空指针检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56838038/

相关文章:

java - 将提交的代码与以前提交的代码进行比较?

java - Java : Find Inappropriate Exception Handling 的 Coverity 静态分析

language-agnostic - 有关用于错误查找的静态分析的良好介绍性文本?

使用指向结构体指针的指针时发生 C 段错误

c - 使用套接字向 C 中的本地 IP 进行 GET 请求

c++ - Clang 和 C++11 header

c++ - boost::uuids::uuid 作为 std::unordered_map 中的键?

c - 如何处理嵌套列表?

c++ - 如何使用 "Tool Tips"捕获屏幕?

c - 有没有办法在单个翻译单元中理智地使用 GCC __attribute__((noreturn)) 和 <stdnoreturn.h> ?