V512. A call of the 'Foo' function will lead to a buffer overflow or underflow

The analyzer found a potential error related to memory buffer filling, copying or comparison. The error might cause a buffer overflow or, vice versa, buffer underflow.

This is a rather common kind of errors that occurs due to misprints or inattention. What is unpleasant about such errors is that a program might work well for a long time. Due to sheer luck, acceptable values might be found in uninitialized memory. The area of writable memory might not be used.

Let's study two samples taken from real applications.

Sample N1.

MD5Context *ctx;
memset(ctx, 0, sizeof(ctx));

Here the misprint causes release of only a part of the structure and not the whole structure. The error is in calculation of the pointer's size and not the whole structure MD5Context. Here is the correct version of the code:

MD5Context *ctx;
memset(ctx, 0, sizeof(*ctx));

Sample N2.

#define CONT_MAP_MAX 50
int _iContMap[CONT_MAP_MAX];
memset(_iContMap, -1, CONT_MAP_MAX);

In this sample, the size of the buffer to be filled is also defined incorrectly. This is the correct version:

#define CONT_MAP_MAX 50
int _iContMap[CONT_MAP_MAX];
memset(_iContMap, -1, CONT_MAP_MAX * sizeof(int));

Note on the strncpy function.

Some programmers are surprised that the analyzer generates the V512 warning on the following code:

char buf[5];
strncpy(buf, "X", 100);

It may seem at first sight that the function is to copy only 2 bytes (the 'X' character and the terminal null). But an array overrun will really occur here. The author of this code has forgotten one thing about the 'strncpy' function. Here is a quotation from the description of this function on the MSDN website: If count is greater than the length of strSource, the destination string is padded with null characters up to length count.

Note about false positives warning.

It turns out for some reason that for some projects the analyzer generates a lot of false positives warning about buffer underflows. Sometimes, on the contrary, all the warnings about buffer overflows appear to be false positives. In this case you may use the fine setting of the diagnostic rule.

It can be done by adding the following comments into the code text where you need:



The first comment disables warnings about underflows, while the second disables warnings about overflows. If you add both, it will be identical to completely disabling the V512 diagnostic rule.

These comments should be added into the header file included into all the other files. For instance, such is the "stdafx.h" file. If you add the comments into the "*.cpp" file, they will affect only this particular file.

You can look at examples of errors from real projects which were detected by this diagnostic message.

Do you make errors in the code?

Check your code
with PVS-Studio

Static code analysis
for C, C++ and C#

goto PVS-Studio;