V708. Dangerous construction is used: 'm[x] = m.size()', where 'm' is of 'T' class. This may lead to undefined behavior.
The analyzer has detected an instant of undefined behavior related to containers of the map type or similar to it.
An example of incorrect code:
std::map<size_t, size_t> m;
....
m[0] = m.size();
This code fragment leads to undefined behavior as the calculation sequence for the operands of the assignment operator is not defined. In case the object already contains an item associated with zero, no troubles will occur. However, if it is absent, program may go on to execute in two different ways depending on the version of the compiler, operating system and so on.
Suppose the compiler will first calculate the right operand of the assignment operator and only after that the left one. Since the container is empty, m.size() returns zero. Zero is then associated with zero and we've got m[0] == 0.
Now suppose the compiler will first calculate the left operand and only then the right one. It is m[0] that will be taken first. Since nothing is associated with zero, an empty association will be created. Then m.size() is calculated. Since the container is not empty anymore, m.size() returns one. After that, one is associated with zero. And the result will be m[0] == 1.
A correct way to fix this code is to use a temporary variable and associate some value with zero in advance:
std::map<size_t, size_t> m;
....
m[0] = 0;
const size_t mapSize = m.size();
m[0] = mapSize;
Despite that this situation is not likely to occur often in real code, it is dangerous in that the code fragment leading to undefined behavior is usually very difficult to spot.
This diagnostic is classified as:
|
You can look at examples of errors detected by the V708 diagnostic. |