Visual Studio 2015 C6386 code analysis warns of buffer overflow

I read a lot about Visual Studio C8386 code analysis warning, but can't figure out this problem with my code. I shortened it to the following small program:

unsigned int nNumItems = 0;

int main()
{
    int *nWords=nullptr;
    unsigned int nTotal;

    nTotal = 3 + 2 * nNumItems;
    nWords = new int[nTotal];

    nWords[0] = 1;
    nWords[1] = 2; // this is line 18, warning C6386

    delete[] nWords;
    return 0;
}

Analyze-> Run Code Analysis-> On Solution will display the following warning:

file.cpp (18): warning C6386: buffer overflow on write to "nWords": the size of the file being written is "nTotal" 4 bytes, but "8" bytes can be written.

It is legal? Now, if I translate my global variable and make it local, the warning will disappear!

int main()
{
    unsigned int nNumItems = 0;
...
}

But I can not do it, as in the full code, this is a member variable.

Similarly, if I translate the nTotal definition to β€œnew int”, I can also remove the warning:

    nWords = new int[3 + 2 * nNumItems];

, nWords .

Visual Studio, ?

+5
3

nNumItems , , , nNumItems SIZE_MAX , . , :

size_t nNumItems = 0;

void foo()
{
    nNumItems = SIZE_MAX;
}
void bar()
{
    const size_t nTotal = 3 + 2 * nNumItems;
    auto nWords = new int[nTotal];

    nWords[0] = 1;
    nWords[1] = 2;
}

int main()
{
    foo();
    bar();

    return 0;
}

, , std::vector<int>.

+2

, 3 + 2 * nNumItems , . , . .

, , , , "", , , .

nWords[1] = 2 nNumItems. , , . , , nWords[0] = 1.

, , , , .

, . , . , , - . , - NP- , , , , , , , , , , .

, :

file.cpp(18): C6386: "nWords": "nTotal" 4 , "8" .

, , nTotal*4 8. , , ,

file.cpp(18): C6386: "nWords": 1024 , "8192".

, nTotal*4, -, , nTotal , , 8. , , - , . , .

//EDIT - : nNumItems < - SIZE_MAX

, SIZE_MAX. SAT- Microsoft, , , - . unsigned int x = SIZE_MAX; std::cout << ( (3+2*x)*sizeof(int) ); 4 (), x, 8.

, Microsoft, , , ((3+2*x)*4) < 8 - . , - :

nTotal * 4 < 8, {nTotal = 1, nNumItems = 4294967295} `

. ... , . , , , , .

+2

const:

const unsigned int nNumItems = 0;
0

Source: https://habr.com/ru/post/1668302/


All Articles