Visual Studio 中的警告 C6385

Chr*_*sMM 5 c++ sal microsoft.codeanalysis visual-studio-2019

我似乎从 Visual Studio 2019(16.5 预览版,但也在 16.4 及更早版本中)代码分析工具收到错误警告消息。这是一个错误,还是我真的只是错过了什么?

生成的警告(确切地说)是:

警告 C6385:从“prodlist”读取无效数据:可读大小为“(size_t)*32+8”字节,但可以读取“64”字节。

这是生成警告的代码(尽可能少)

#include <cstdint>
#include <string>
#include <iostream>

struct Product {
    std::string price_profile;
};

int getNumRows() {
    return 5;
}

Product *getProductsFromDB( int &numelements ) {
    numelements = 0;

    const int num_rows = getNumRows();
    if ( num_rows == 0 ) {
        numelements = 0;
        return nullptr;
    }

    Product *prodlist = new Product[num_rows];
    for ( int i = 0; i < num_rows; ++i ) {
        prodlist[i].price_profile = "test"; // Warning on this line
    }
    numelements = num_rows;

    return prodlist;
}

int main() {
    int num_rows;
    Product *prodlist = getProductsFromDB( num_rows );
    for ( int i = 0; i < num_rows; ++i ) {
        std::cout << prodlist[i].price_profile;
    }

    getchar();
}
Run Code Online (Sandbox Code Playgroud)

如果我将 更改price_profile为 an int(及其相应的值),或者如果我更改num_rows为常量(如5),则警告消失。

Gov*_*mar 6

似乎在 Visual Studio 2019 中,微软默认对 C 和 C++ 代码强制执行 SAL 分析规则,尽管这里仍然有很多误报,比如你的情况。

您现在可以做的一件事是禁用给出误报的警告:

#pragma warning(push)
#pragma warning(disable:6385)
Product *getProductsFromDB( int &numelements ) {
 ...
}
#pragma warning(pop)
Run Code Online (Sandbox Code Playgroud)

  • 我知道我可以禁用它,对我来说,它只会在我运行 CA 工具时生成警告。我想知道这是否是误报,或者实际上是我的代码中的错误。 (2认同)