Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

In this non-compliant code, the floating point variables d, e and f are not initialized correctly because the division operation takes place on two integer types and hence the result is truncated to nearest decimal point.

Code Block
bgColor#FFCCCC
#include<stdio.h>

void main()
{
    short a;
    int b;
    long c;

    float d;
    double e;
    double f;

    a=533;
    b=6789;
    c=466438237;

    d=a/7;
    e=b/30;
    f=c/789;

    printf("Value of d is %f\n", d);  // Incorrect value of d i.e.     76.000000 is printed
    printf("Value of e is %f\n", e);  // Incorrect value of e i.e.    226.000000 is printed
    printf("Value of f is %f\n", f);  // Incorrect value of f i.e. 591176.000000 is printed
}

Compliant Code Solution 1

In this compliant code, we remove the decimal error in initialization by making the division operation to involve at least one floating point operand. Hence, the result of the operation is the correct floating point number.

Code Block
bgColor#CCCCFF
#include<stdio.h>

void main()
{
    short a;
    int b;
    long c;

    float d;
    double e;
    double f;

    a=533;
    b=6789;
    c=466438237;

    d=a/7.0f;
    e=b/30.0f;
    f=c/789.0f;

    printf("Value of d is %f\n", d);  // Correct value of d i.e.     76.142860 is printed
    printf("Value of e is %f\n", e);  // Correct value of e i.e.    226.300000 is printed
    printf("Value of f is %f\n", f);  // Correct value of f i.e. 591176.472750 is printed
}

Compliant Code Solution 2

In this compliant code, we remove the decimal error in initialization by first storing the integer in the floating point variable and then performing the division operation. This ensures that atleast one of the operands is a floating point number and hence, the result is the correct floating point number.

Code Block
bgColor#CCCCFF

#include<stdio.h>

void main()
{
    short a;=533;
    int b;=6789;
    long c;=3269326;

    float d;
    double e;
    double f;

    a=533;
    b=6789;
    c=466438237;

    d=a;
    e=b;
    f=c;
    d/=7;
    e/=30;
    f/=789;

    printf("Value of d is %f\n", d);  // Correct value of d i.e.     76.142860 is printed
    printf("Value of e is %f\n", e);  // Correct value of e i.e.    226.300000 is printed
    printf("Value of f is %f\n", f);  // Correct value of f i.e. 591176.472750 is printed
}

Risk Assessment Summary

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

FLP33-C

1 (low)

2 (probable)

1 (high)

P2

L3

...