警告 C6031

忽略返回值:“被调用函数”可能返回意外值

备注

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

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

此警告同时适用于 C 和 C++ 代码。

代码分析名称:RETVAL_IGNORED_FUNC_COULD_FAIL

示例

下面的代码生成警告 C6031:

#include <stdio.h>
int main()
{
    fopen("test.c", "r"); // C4996, C6031 return value ignored
    // code ...
}

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

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

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

#include <stdio.h>
int main()
{
    FILE* stream;
    errno_t err;

    if ((err = fopen_s(&stream, "test.c", "r")) != 0)
    {
        // code ...
    }
}

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

#include <sal.h>
_Check_return_ bool func()
{
    return true;
}

int main()
{
    func();
}

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

#include <sal.h>
_Check_return_ bool func()
{
    return true;
}

int main()
{
    if (func())
    {
        // code ...
    }
}

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

#include <tuple>
#include <ctime>
#include <cstdlib>
#include <stdio.h>

int main()
{
    std::srand(static_cast<unsigned int>(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 注释减少代码缺陷