6

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.

ChrisMM
  • 8,448
  • 13
  • 29
  • 48
  • In addition to the above: When trying to use static code analysis we've seen the code emit warning if we used the following array indexing, on dynamically allocated arrays: `array[i]`, but it went away, if we changed it to `*(array + i)`, which should, technically, evaluate to the same thing.. – Algirdas Preidžius Jan 08 '20 at 16:28
  • @anatolyg, updated to include the full version. – ChrisMM Jan 08 '20 at 16:30
  • 1
    Just to spell it out explicitly: The line in question is undoubtedly correct. This is a clear false positive. – Max Langhof Jan 08 '20 at 16:32

1 Answers1

7

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)
Govind Parmar
  • 20,656
  • 7
  • 53
  • 85
  • 2
    I know I can disable it, and for me it only generates a warning when I run the CA tool. I'm wondering if it is a false positive, or if it's actually an error in my code. – ChrisMM Jan 08 '20 at 16:29
  • @ChrisMM It's a false positive. – Govind Parmar Jan 08 '20 at 16:33
  • 1
    Thanks. I'll report the issue to MS, and hope they fix it. I have about 10 of these currently suppressed in my code :( – ChrisMM Jan 08 '20 at 16:45