相关文章推荐
开心的机器人  ·  android - Error AAPT2 ...·  1 年前    · 
火星上的海豚  ·  google.auth.exceptions ...·  1 年前    · 
慷慨大方的西装  ·  《SVTR: Scene Text ...·  1 年前    · 
小胡子的羽毛球  ·  Hackthebox - ...·  1 年前    · 

警告 C6031 指示调用方未检查失败的函数返回值。 根据调用的函数,此缺陷可能导致看似随机的程序错误行为。 这包括错误情况或资源不足情况下的崩溃和数据损坏。

一般来说,如果对某些函数的调用会需要磁盘、网络、内存或其他资源,则不能放心地假设这些调用一定会成功。 调用方应始终检查返回值并适当地处理错误情况。 还要考虑使用 _Must_inspect_result_ 批注,以检查该值是否用一种有效的方式检查。

代码分析名称: RETVAL_IGNORED_FUNC_COULD_FAIL

以下代码生成警告 C6031:

#include <stdio.h>
void f( )
    fopen( "test.c", "r" ); // C4996, C6031 return value ignored
    // code ...

要更正此警告,请检查函数的返回值,如以下代码所示:

#include <stdio.h>
void f( )
    FILE *stream;
    if ( (stream = fopen( "test.c", "r" )) == NULL )
        return;
    // code ...

以下代码使用安全函数 fopen_s 来更正此警告:

#include <stdio.h>
void f( )
    FILE *stream;
    errno_t err;
    if ( (err = fopen_s( &stream, "test.c", "r" )) !=0 )
        // code ...

如果调用方忽略使用 _Check_return_ 属性批注的函数的返回值,也会生成此警告,如下面的代码所示。

#include <sal.h>
_Check_return_ bool func();
void test_f()
    func(); //  Warning C6031

要更正之前的警告,请检查返回值,如以下代码所示:

#include <sal.h>
_Check_return_ bool func();
void test_f()
    if ( func() ) {
        // code ...

如果需要忽略函数的返回值,请将返回的值 std::ignore分配给 。 分配到 std::ignore 清楚地表明开发人员的意图并有助于将来的代码维护。

#include <tuple>
#include <ctime>
#include <stdio.h>
void f()
    std::srand(static_cast(std::time(nullptr))); // set initial seed value to system clock
    std::ignore = std::rand(); // Discard the first result as the few random results are always small.
    // ... 

fopen_s, _wfopen_s
使用 SAL 注释减少代码缺陷