Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warning C6385 in Visual Studio

I seem to get an erroneous warning message from Visual Studio 2019 (16.5 Preview but also in 16.4 and earlier) Code Analysis tool. Is this a bug, or am I really just missing something?

The warning generated (exactly) is:

warning C6385: Reading invalid data from 'prodlist': the readable size is '(size_t)*32+8' bytes, but '64' bytes may be read.

Here's the code which generates the warning (as minimal as possible)

#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();
}

If I change the price_profile to an int (and its corresponding value), or if I change num_rows to a constant (like 5) then the warning goes away.

like image 358
ChrisMM Avatar asked Jan 08 '20 16:01

ChrisMM


Video Answer


1 Answers

It seems in Visual Studio 2019 Microsoft is enforcing SAL analysis rules on C and C++ code by default, even though there are still plenty of false positives like your case here.

One thing you can do for now is disable the warning giving a false positive:

#pragma warning(push)
#pragma warning(disable:6385)
Product *getProductsFromDB( int &numelements ) {
 ...
}
#pragma warning(pop)
like image 136
Govind Parmar Avatar answered Oct 07 '22 01:10

Govind Parmar