PRECISION.LOSS.INIT

Loss of precision during initialization

The PRECISION.LOSS.INIT defect is reported when an implicit cast to a smaller data type during initialization may cause a loss of precision (data).

Vulnerability and risk

Depending on the exact circumstances, this situation is potentially exploitable, for instance if it results in a buffer overflow.

Mitigation and prevention

If the loss of precision cast is intentional, the source of the cast should be masked with an appropriate bitmask. For example:

Copy
char c = (i & 0xFF);

Vulnerable code example

Copy
void foo(int i) {
    char c = i; // PRECISION.LOSS.INIT
}

Klocwork flags a PRECISION.LOSS.INIT defect at line 2, in which an int is converted to char.

Fixed code example

Copy
void foo(int i) {
    char c = (i & 0xFF);
}

Klocwork no longer flags a PRECISION.LOSS.INIT defect at line 2 because the source of the cast is masked with an appropriate bitmask.

Security training

Application security training materials provided by Secure Code Warrior.