V1029. Numeric Truncation Error. Return value of function is written to N-bit variable.


The analyzer has detected a situation where the length of a container or string is stored to a 16-bit or 8-bit variable. This is dangerous because even with small data, the size value may not fit into the variable, thus causing an error.

Consider the following example:

std::string str;
....
short len = str.length();

We must use type 'size_t' as it guarantees to exactly fit the size of any string/container:

size_t len = str.length();

Or, if we want to be meticulous, type 'std::string::size_type':

std::string::size_type len = str.length();

Or we could use the 'auto' keyword:

auto len = str.length();

This defect might seem harmless. The programmer may assume that the string simply cannot be too long in any reasonable scenario. But what they do not take into account is that such data truncation can be intentionally exploited as a vulnerability. That is, an intruder could find a way to feed invalid input data to get oversized strings. Incorrect handling of such strings by the program could then enable them to manipulate its behavior. In other words, this defect is a potential vulnerability and must be fixed.

Some users say that the analyzer is not correct, issuing a warning for the following code:

size = static_cast<unsigned short>(array->size());

They think that if there is 'static_cast', then everything is fine and a developer knows what he is doing. However, it is possible that by using type casting someone was struggling with a compiler warning. By doing so, 'static_cast' only covers up the problem, but does not eliminate it.

If in a project there is a lot of code, where such type castings are used and you trust this code, you can just disable the 1029 diagnostic. Another option is to disable warnings exactly for the cases, where 'static_cast' is used. To do it, you can write in one of global header files or in the diagnostics configuration file (.pvsconfig) the following comment:

//-V:static_cast:1029

Note. Diagnostic V1029 ignores cases when the size is stored to a 32-bit variable. These are detected by diagnostics that search for 64-bit related error patterns. See the "Diagnosis of 64-bit errors (Viva64, C++)" diagnostics set in the documentation.

According to Common Weakness Enumeration, potential errors found by using this diagnostic are classified as CWE-197.


Bugs Found

Checked Projects
364
Collected Errors
13 504